iOS解NSArray,NSDictionary unicode
2017-05-02 本文已影响0人
ashura_
问题
看代码
//创建数组
NSArray *array = @[@"abc",@"中文"];
//创建字典
NSDictionary *dict = @{@"key1" : @"abc",
@"key2" : @"中文",
};
//打印数组和字典
NSLog(@" \n dict = %@ \n array = %@",dict,array);
结果
(lldb) po array
<__NSArrayI 0x7fc6e420d620>(
abc,
中文
)
(lldb) po dict
{
key1 = abc;
key2 = "\U4e2d\U6587";
}
2016-12-20 13:58:18.492 TSUnicodeFormant[55360:1772807]
dict = {
key1 = abc;
key2 = "\U4e2d\U6587";
}
array = (
abc,
"\U4e2d\U6587"
)
(lldb)
结论
类型 | NSArray | NSDictionary |
---|---|---|
NSLog | unicode码 | unicode码 |
Po | 正常 | unicode码 |
NSLog与po的的表现不尽一致,所以对NSDictionary要进行两方面处理。
分析
国际惯例,当遇到问题时候。四个步骤apple Document->google->github->百度
查看文档
- 已知其实无论
NSLog
还是po
,都会调用description
方法,description
是NSObject
的方法。
所以以description
搜索,找到descriptionWithLocale:
(NSArray,NSDictionary都有)
Returns a string object that represents the contents of the dictionary, formatted as a property list.
解决方案
重写descriptionWithLocale:
,这里写在分类里
-(NSString *)descriptionWithLocale:(id)locale
{
NSMutableString *msr = [NSMutableString string];
[msr appendString:@"["];
for (id obj in self) {
[msr appendFormat:@"\n\t%@,",obj];
}
//去掉最后一个逗号(,)
if ([msr hasSuffix:@","]) {
NSString *str = [msr substringToIndex:msr.length - 1];
msr = [NSMutableString stringWithString:str];
}
[msr appendString:@"\n]"];
return msr;
}
进行测试,
(lldb) po dict
{
key1 = abc;
key2 = "\U4e2d\U6587";
}
2016-12-20 14:35:48.002 TSUnicodeFormant[56085:1799830]
dict = {
key1 = abc,
key2 = 中文
}
array = [
abc,
中文
]
(lldb)
可以看出,就剩下po有问题了。
万般无奈,只能用黑魔法了。首先在项目导入 JRSwizzle 库,在合理的地方,加入
[NSDictionary jr_swizzleMethod:@selector(description) withMethod:@selector(my_description) error:nil];
在分类里对description
进行置换
- (NSString*)my_description {
NSString *desc = [self my_description];
desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
return desc;
}
完美结果
(lldb) po dict
{
key1 = abc;
key2 = "中文";
}
2016-12-20 14:41:25.558 TSUnicodeFormant[56284:1805511]
dict = {
key1 = abc,
key2 = 中文
}
array = [
abc,
中文
]
(lldb)
Demo
git
地址TSUnicodeFormant