On Jun 5, 2015, at 10:02 PM, Carl Hoefs <[email protected]> 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 protected])

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:
https://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to [email protected]

Reply via email to