Question

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.
Was it helpful?

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”.

OTHER TIPS

As an answer to the comment in the other answer, I would recommend the poster to

  • generate a UTF8 string in a portable way into char*
  • and, at the last minute, convert it to CFString using CFStringCreateWithCString with kCFStringEncodingUTF8 as the encoding.

Please, please do not use %s in CFStringCreateWithFormat. Please do not rely on the "system encoding", which is MacRoman on Western European environments, but not in other languages. The concept of the system encoding is inherently brain-dead, especially in east Asian environments (which I came from) where even the characters inside ASCII code range (below 127!) is modified. Hell breaks loose if you rely on "system encoding". Fortunately, since 10.4, all of the methods which use "system encoding" are now deprecated, except %s... .

I'm sorry I write this much for this small topic, but it was a real pity a few years ago when there were many nice apps which didn't work on Japanese/Korean Macs because of just this "system encoding." Please refer to this detailed explanation which I wrote a few years ago, if you're interested.

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