电脑相关iOS 开发每天分享优质文章iOS学习开发

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

2017-11-28  本文已影响153人  CodeGeass

创建数组的分类

@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

创建字典的分类

@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
上一篇 下一篇

猜你喜欢

热点阅读