Objective-C NSString 编码变音
我遇到以下问题:
我在 UITextField 中输入数据,然后想将其发送到服务器。但我输入的数据可能包含变音符号(ö、ä、ü、...)。然后我在将其传递到服务器时得到错误的编码。但我用UTF8编码。
NSString *s = @"ö";
NSLog(@"%@", s);
NSLog(@"%s", s.UTF8String);
我做错了什么?在第二行中,我看到一个完美的“ö”,但在第三行中,我看到这个: √∂
互联网上有很多编码帖子,但没有一个真正解决了问题。
I have the following issue:
I enter data in a UITextField and then I want to send it to a server. But the data I am entering may contain umlauts (ö, ä, ü, …). Then I get a wrong encoding when passing it to the server. But I am encoding it with UTF8.
NSString *s = @"ö";
NSLog(@"%@", s);
NSLog(@"%s", s.UTF8String);
What am I doing wrong? In the second line, I see a perfectly fine "ö", but in the third line, I see this: √∂
There are a lot of encoding posts around the Internet, but nothing really solved the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
与服务器通信时,您是否正确编码或解码?
请记住 NSString 具有这些出色的功能:
stringByAddingPercentEscapesUsingEncoding:
和
stringByReplacingPercentEscapesUsingEncoding:
至于在第三个 NSLog 行输出中看到垃圾,格式中的“%s”意味着 NSLog 需要 C 风格的字节集合,并且它可能无法正确显示高 ASCII 值。而 NSLogs 中的“%@”格式意味着 NSString 对象,并且所有字符串编码都应该正常工作。
Are you encoding or decoding things properly when talking to your server?
Remember that NSString has those wonderful functions:
stringByAddingPercentEscapesUsingEncoding:
and
stringByReplacingPercentEscapesUsingEncoding:
As for seeing garbage in that third NSLog line output, the "%s" in the format means NSLog is expecting a C-style collection of bytes and it might not be able to display high-ascii values properly. Whereas "%@" format in NSLogs means NSString objects and all string encodings should work properly for that.
处理 UTF8 和 NSString 时,您可能应该使用
[@"ö" dataUsingEncoding:NSUTF8StringEncoding]
来获取可以通过网络发送的 NSData 对象。这总是工作得很好。When dealing with UTF8 and NSString, you should probably use
[@"ö" dataUsingEncoding:NSUTF8StringEncoding]
to get the NSData object you can send over the network. This will always work fine.