美文网首页
解决打印数组、字典时中文乱码

解决打印数组、字典时中文乱码

作者: 深蓝_S | 来源:发表于2016-06-07 17:12 被阅读232次

数组

在iOS开发中,经常需要查看数组中得元素是否是自己想要的,但是苹果并没有对直接打印数组中得中文作处理,直接打印就会出现一堆很讨厌的东西,解决其实很简单,就是需要通过为NSArray添加分类
重写 - (NSString *)descriptionWithLocale:(id)locale方法即可

代码:
#import "NSArray+Log.h"

@implementation NSArray (Log)
- (NSString *)descriptionWithLocale:(id)locale
{
    NSMutableString *str = [NSMutableString stringWithFormat:@"%lu (\n", (unsigned long)self.count];
    
    for (id obj in self) {
        [str appendFormat:@"\t%@, \n", obj];
    }
    
    [str appendString:@")"];
    return str;
}
@end

字典

同理要解决NSDictionary乱码问题,也需要为NSDictionary类添加一个分类
重写 - (NSString *)descriptionWithLocale:(id)locale方法

代码:

#import "NSDictionary+Log.h"

@implementation NSDictionary (Log)
- (NSString *)descriptionWithLocale:(id)locale{    
NSArray *allKeys = [self allKeys];    
NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"{\t\n "];    
for (NSString *key in allKeys) {     
   id value= self[key];      
  [str appendFormat:@"\t \"%@\" = %@,\n",key, value];    
}  
  [str appendString:@"}"];      

 return str;
}
@end

相关文章

网友评论

      本文标题:解决打印数组、字典时中文乱码

      本文链接:https://www.haomeiwen.com/subject/tfnddttx.html