iOS UTF-8标签字符串 [英] iOS UTF-8 Label String

查看:322
本文介绍了iOS UTF-8标签字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在标签中显示的UTF-8编码字符串.

I have a UTF-8 encoding string that I want to display in a label.

当我设置一个断点并检查包含字符串的变量时,一切看起来都不错.但是,当我尝试输出到日志或标签时,会得到拉丁编码.

When I set a break-point and examine the variable holding the string, all looks good. However, when I try to output to the log, or to the label, I get latin encoding.

我已经尝试了关于SO以及其他方面的几乎所有建议,但是我只是无法使字符串正确显示.

I have tried almost every suggestion on SO and beyond, but I just cannot get the string to display properly.

这是我的代码:

NSString *rawString = [NSString stringWithFormat:@"%@",m_value];

const char *utf8String = [rawString UTF8String];
NSLog (@"%@", [NSString stringWithUTF8String:utf8String]);
NSLog (@"%s", utf8String);
NSLog (@"%@", rawString);

self.resultText.text = [NSString stringWithUTF8String:utf8String];

m_value是一个NSString,在调试窗口中,它还会显示正确的编码.

m_value is an NSString, and in the debug window, it also displays the correct encoding.

m_value NSString *  0x006797b0 @"鄧樂愚..."
    NSObject    NSObject    
    isa Class   0x3bddd8f4
    [0] Class   

我正在使用iOS 6.1 SDK.

I am using the iOS 6.1 SDK.

推荐答案

所以我终于设法了解了这一点.

So I finally managed to get to the bottom of this.

m_value NSString由我无法访问源的第三方库设置.即使已在调试面板中(即显示汉字)正确解码了此变量的值,该字符串实际上仍使用NSMacOSRomanStringEncoding进行了编码.

The m_value NSString was being set by a third party library to which I had no access to the source. Even though the value of this variable was being decoded correctly in the (I.e. displaying the Chinese characters) in the debug panel, the string was actually encoded with NSMacOSRomanStringEncoding.

通过将输出复制到 TextWrangler 并翻转编码直到我找到了一种可以正确转换为UTF-8的文件.

I was able to determine this by copying the output into TextWrangler, and flipping encodings until I found the one that translated correctly into UTF-8.

然后要在Objective-C中修复,我首先将NSString转换为const char:

Then to fix in Objective-C, I first translated the NSString to a const char:

const char *macString = [bxr.m_value cStringUsingEncoding:NSMacOSRomanStringEncoding];

然后转换回NSString:

NSString *utf8String = [[NSString alloc]initWithCString:macString encoding:NSUTF8StringEncoding];

+1到@Vitaly_S和@iphonic,他们的回答最终使我想到了这个解决方案.对于任何偶然发现此问题的人;从Xcode 4.6.1开始,似乎无法信任调试窗口来正确呈现字符串,但是您可以依靠NSLog输出.

+1 to @Vitaly_S and @iphonic whose answers eventually led me to this solution. For anyone else that stumbles across this; it seems that as of Xcode 4.6.1, the debug window cannot be trusted to render strings correctly, but you can rely on the NSLog output.

这篇关于iOS UTF-8标签字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆