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

2018-07-05  本文已影响28人  iOSCoder_XH

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

上一篇下一篇

猜你喜欢

热点阅读