1.前言
在开发中,我们经常会进行打印调试,但是有时候你会发现打印的内容并不是你想要的,因为它们是Unicode码(入下图),如何将打印信息转成中文呢,下面我给大家提供一种方法。
2.解决方法
我们一般打印的信息是数组信息和字典信息,它们的信息量比较多,与后台交互也多是转成这两种数据类型,我们分别创建它们的分类,然后重写 - (NSString *)descriptionWithLocale:(id)locale方法,在这里进行打印的调整,具体代码如下:
- NSDictionary
#import "NSDictionary+DLog.h"
@implementation NSDictionary (DLog)
// log NSSet with UTF8
// if not ,log will be \Uxxx
- (NSString *)descriptionWithLocale:(id)locale{
if (![self count]) {
return @"";
}
NSString *tempStr1 =
[[self description] stringByReplacingOccurrencesOfString:@"\\u"
withString:@"\\U"];
NSString *tempStr2 =
[tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
NSString *tempStr3 =
[[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
NSString *str =
[NSPropertyListSerialization propertyListWithData:tempData
options:NSPropertyListImmutable
format:NULL
error:NULL];
return str;
}
@end
- NSArray
#import "NSArray+Dlog.h"
@implementation NSArray (Dlog)
-(NSString *)descriptionWithLocale:(id)locale{
NSMutableString *string = [NSMutableString string];
// 开头有个[
[string appendString:@"[\n"];
// 遍历所有的元素
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[string appendFormat:@"\t%@,\n", obj];
}];
// 结尾有个]
[string appendString:@"]"];
// 查找最后一个逗号
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
if (range.location != NSNotFound)
[string deleteCharactersInRange:range];
return string;
}
@end