iOS 打印字典和数组中的中文

创建数组的分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@implementation NSArray (ZDLogHelper)

#ifdef DEBUG
// NSLog数组对象时会调用此方法,将里面的中文在控制台打印出来
- (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level {
if ([NSJSONSerialization isValidJSONObject:self]) {
NSString *logString;
@try {
logString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
} @catch (NSException *exception) {
logString = [NSString stringWithFormat:@"打印数组时转换失败:%@",exception.reason];
} @finally {
return logString;
}
}
NSMutableString *string = [NSMutableString stringWithString:@"{\n"];
[self enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
[string appendFormat:@"\t%@,\n", obj];
}];
[string appendString:@"}\n"];
return string;
}
#endif

@end

创建字典的分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@implementation NSDictionary (ZDLogHelper)

#ifdef DEBUG
// NSLog字典对象时会调用此方法,将里面的中文在控制台打印出来
- (NSString *)descriptionWithLocale:(nullable id)locale indent:(NSUInteger)level {
// 此注释掉的版本有缺陷,当self里面包含json转换不支持的类型时会报错:Invalid type in JSON write
/*
NSString *logString;
@try {
logString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
} @catch (NSException *exception) {
logString = [NSString stringWithFormat:@"打印字典时转换失败:%@",exception.reason];
} @finally {
return logString;
}
*/

// 以下为两种方式结合处理
if ([NSJSONSerialization isValidJSONObject:self]) {
NSString *logString;
@try {
logString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
} @catch (NSException *exception) {
logString = [NSString stringWithFormat:@"打印字典时转换失败:%@",exception.reason];
} @finally {
return logString;
}
}

NSMutableString *string = [NSMutableString stringWithString:@"{\n"];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[string appendFormat:@"\t%@ = %@;\n", key, obj];
}];
[string appendString:@"}\n"];
return string;
}
#endif

@end

iOS 打印字典和数组中的中文
http://example.com/2017/09/21/iOS-打印字典和数组中的中文/
作者
guanzhendong
发布于
2017年9月21日
许可协议