decoding a UTF-8 NSString
October 30, 2009
I came across this issue when I received a UTF-8 encoded string from a URL. I was expecting the UTF-8 string to be automatically decoded, but then I realized that it’s probably not trivial to identify a UTF-8 string, so NSString doesn’t automatically do this for a reason. (Unfortunately, this realization came only after I’d been banging my head against the screen for an hour. Hence this post
There’s no method in the NSString API to decode a UTF-8 NSString directly, so first it has to be converted to a C string (gotta love those C strings.)
NSString *encodedString; NSString *decodedString = [NSString stringWithUTF8String:[encodedString cStringUsingEncoding:[NSString defaultCStringEncoding]]];
You are a champ!