【发布时间】:2014-05-15 07:36:53
【问题描述】:
我注意到,如果我尝试使用格式说明符“%s”打印包含 UTF-8 字符串表示的字节数组,printf() 会正确,但NSLog() 会出现乱码(即,每个字节都按原样打印,例如“¥”被打印为 2 个字符:“¬•”)。
这很好奇,因为我一直以为NSLog()就是printf(),加上:
- 第一个参数(“格式”)是 Objective-C 字符串,而不是 C 字符串(因此是“@”)。
- 前置的时间戳和应用程序名称。
- 在末尾自动添加换行符。
- 能够打印 Objective-C 对象(使用格式“%@”)。
我的代码:
NSString* string;
// (...fill string with unicode string...)
const char* stringBytes = [string cStringUsingEncoding:NSUTF8Encoding];
NSUInteger stringByteLength = [string lengthOfBytesUsingEncoding:NSUTF8Encoding];
stringByteLength += 1; // add room for '\0' terminator
char* buffer = calloc(sizeof(char), stringByteLength);
memcpy(buffer, stringBytes, stringByteLength);
NSLog(@"Buffer after copy: %s", buffer);
// (renders ascii, no matter what)
printf("Buffer after copy: %s\n", buffer);
// (renders correctly, e.g. japanese text)
不知何故,看起来printf() 比NSLog() 更“聪明”。有谁知道根本原因,以及是否在任何地方记录了此功能? (没找到)
【问题讨论】:
-
当然,实际的解决方案是将
NSLogUTF8 字符串作为NSString,not 作为C 字符串。但在这种特殊情况下,我想检查char缓冲区是否被正确复制。
标签: ios objective-c utf-8 printf nslog