Question

I have the following code in my Application:

static void foo(CFStringRef str)
{
    CFStringEncoding encoding = CFStringGetSystemEncoding();
    const char * cString = CFStringGetCStringPtr(str, encoding);

    //.....                
}

It's been around since iOS 5, and always worked. Since iOS 7 release, CFStringGetCStringPtr returns NULL. Adding the following code, have solved it:

if (cString==NULL)
{
    cString = [
        ((NSString *)str) cStringUsingEncoding:[NSString defaultCStringEncoding]
    ];
}

Still, I would like to know if anyone knows what causes the problem?

Was it helpful?

Solution

CFStringGetCStringPtr() isn't guaranteed to return non-NULL. From the docs (emphasis added):

Whether or not this function returns a valid pointer or NULL depends on many factors, all of which depend on how the string was created and its properties. In addition, the function result might change between different releases and on different platforms. So do not count on receiving a non-NULL result from this function under any circumstances.

Always have a fallback to CFStringGetCString(), but even better, use Objective-C and NSString's helper methods (e.g. UTF8String).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top