• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Using CFSTR() with const char * variable
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Using CFSTR() with const char * variable


  • Subject: Re: Using CFSTR() with const char * variable
  • From: Ken Thomases <email@hidden>
  • Date: Fri, 05 Jun 2015 22:17:24 -0500

On Jun 5, 2015, at 10:02 PM, Carl Hoefs <email@hidden> wrote:

> If I use CFSTR() in the following way:
>    CFStringRef mystr = CFSTR( "This is a string" );
> there is no problem.
>
> However, if I use a variable instead of “string” Xcode flags this as an error:
>    const char *mystring = "This is a string";
>    CFStringRef mystr = CFSTR( mystring );
>                               ^           <— Expected ")"
>
> In CFString.h, CFSTR is defined as:
>    #define CFSTR(cStr)  __CFStringMakeConstantString("" cStr "")
>
> Is it possible to use CFSTR() with a const char * variable?

No.  As you can see from the quoted macro definition, it relies on concatenation of adjacent string literals.

You should use an appropriate CFStringCreate…() function to create a CFString from the C string.  Or just create a CFString or NSString literal from the start.

Be careful with CFStringCreateWithCStringNoCopy(…, kCFAllocatorNull), which you might be tempted to use.  Only use that with pointer to static storage.  The mystring variable in your example does point to static storage, but could be changed to point to something else (it's a pointer to const char, not a const pointer to const char).

Something like this is _not_ safe:

    const char mystring[] = "This is a string";

That is auto-lifetime storage allocated on the heap, which will be deallocated at end of scope.

This would be safe:

    static const char mystring[] = "This is a string";

Regards,
Ken


_______________________________________________

Cocoa-dev mailing list (email@hidden)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden


  • Follow-Ups:
    • Re: Using CFSTR() with const char * variable
      • From: Carl Hoefs <email@hidden>
References: 
 >Using CFSTR() with const char * variable (From: Carl Hoefs <email@hidden>)

  • Prev by Date: Re: Using CFSTR() with const char * variable
  • Next by Date: Re: Using CFSTR() with const char * variable
  • Previous by thread: Re: Using CFSTR() with const char * variable
  • Next by thread: Re: Using CFSTR() with const char * variable
  • Index(es):
    • Date
    • Thread