Search code examples
macosunicodeprintfcfstring

What kind of strings does CFStringCreateWithFormat expects as arguments?


The below example should work with Unicode strings but it doesn't.


CFStringRef aString =  CFSTR("one"); // in real life this is an Unicode string
CFStringRef formatString = CFSTR("This is %s example"); // also tried %S but without success
CFStringRef resultString = CFStringCreateWithFormat(NULL, NULL, formatString, aString);

// Here I should have a valid sentence in resultString but the current result is like aString would contain garbage.

Solution

  • Use %@ if you want to include a CFStringRef via CFStringCreateWithFormat.

    See the Format Specifiers section of Strings Programming Guide for Core Foundation.

    • %@ is for Objective C objects, OR CFTypeRef objects (CFStringRef is compatible with CFTypeRef)
    • %s is for a null-terminated array of 8-bit unsigned characters (i.e. normal C strings).
    • %S is for a null-terminated array of 16-bit Unicode characters.

    A CFStringRef object is not the same as “a null-terminated array of 16-bit Unicode characters”.