美文网首页
Xcode控制台日志输出中文(标准json格式)

Xcode控制台日志输出中文(标准json格式)

作者: iOSCoder_XH | 来源:发表于2018-07-05 17:01 被阅读28次

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方法,当然也可通过类似方法来打印对象信息等,让日志更清晰!

相关文章

网友评论

      本文标题:Xcode控制台日志输出中文(标准json格式)

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