stefanosn
stefanosn

Reputation: 3324

objective c UTF8String not working with japanese

I would like to show the NSString below on my UILabel:

NSString *strValue=@"你好";

but i can not show it on my UILabel i get strange characters!

I use this code to show the text:

[NSString stringWithCString:[strValue UTF8String] encoding:NSUTF8StringEncoding];

I tried [NSString stringWithCString:[strValue cStringUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] and it worked

but i can not show emoticons with cStringUsingEncoding:NSISOLatin1StringEncoding so i have to use UTF8String.

Any help appreciated.

Upvotes: 1

Views: 1085

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185801

Your source file is in UTF-8, but the compiler you are using thinks it's ISO-Latin 1. What you think is the string @"你好" is actually the string @"你好". But when you ask NSString* to give you this back as ISO-Latin 1, and treat it as UTF-8, you've reversed the process the compiler took and you end up with the original string.

One solution that you can use here is to tell your compiler what encoding your source file is in. There is a compiler flag (for GCC it's -finput-charset=UTF-8, not sure about clang) that will tell the compiler what encoding to use. Curiously, UTF-8 should be the default already, but perhaps you're overriding this with a locale.

A more portable solution is to use only ASCII in your source file. You can accomplish this by replacing the non-ASCII chars with a string escape using \u1234 or \U12345678. In your case, you'd use

NSString *strValue=@"\u4F60\u597D";

Of course, once you get your string constant to be correct, you can ditch the whole encoding stuff and just use strValue directly.

Upvotes: 2

Related Questions