Xcode控制台打印日志时,打印NSDictionary和NSArray都不是标准json格式而且不能显示中文,解决方案如下:
@implementation NSDictionary (log)
- (NSString *)descriptionWithLocale:(id)locale{
NSString *logStr = @"";
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
logStr = json;
}
return logStr;
}
@end
@implementation NSArray (log)
- (NSString *)descriptionWithLocale:(id)locale{
NSString *logStr = @"";
if ([NSJSONSerialization isValidJSONObject:self]) {
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
logStr = json;
}
return logStr;
}
@end
通过增加NSDictionary和NSArray的分类来重写其对应的description方法,当然也可通过类似方法来打印对象信息等,让日志更清晰!
网友评论