How to handle 32bit unicode characters in a NSString

Viewed 1420

I have a NSString containing a unicode character bigger than U+FFFF, like the MUSICAL SYMBOL G CLEF symbol ''. I can create the NSString and display it.

NSString *s = @"A\U0001d11eB";  // "AB"
NSLog(@"String = \"%@\"", s);

The log is correct and displays the 3 characters. This tells me the NSString is well done and there is no encoding problem.

    String = "AB"

But when I try to loop through all characters using the method

- (unichar)characterAtIndex:(NSUInteger)index

everything goes wrong.

The type unichar is 16 bits so I expect to get the wrong character for the musical symbol. But the length of the string is also incorrect!

NSLog(@"Length = %d", [s length]);
for (int i=0; i<[s length]; i++)
{
    NSLog(@"  Character %d = %c", i, [s characterAtIndex:i]);
}

displays

    Length = 4
      Character 0 = A
      Character 1 = 4
      Character 2 = .
      Character 3 = B

What methods should I use to correctly parse my NSString and get my 3 unicode characters? Ideally the right method should return a type like wchar_t in place of unichar.

Thank you

1 Answers
Related