Xcode控制台中文问题

在开发中我们经常需要在控制台中打印出一些数据,以验证我们代码的正确性。一般我们的需求都是会打印出网络请求的返回结果,返回的大部分都是json数据,但是直接输出json数据时中文总会以原始码文显示,而不是正常显示中文。

head =  {
            "is_auth" = "1.0";
            "last_pack" = "1.0";
            message = "\U64cd\U4f5c\U6210\U529f";
         }

打印出的都是unicode编码,非常不方便我们迅速的理解。此时其实打印的结果基本没什么意义了。我们需要的是这样

"head" : {
      "is_auth" : "1.0",
      "last_pack" : "1.0",
      "message" : "操作成功",
      }
解决办法
  • 使用代码
    直接将json数据或者字典转换为NSData
// json数据或者NSDictionary转为NSData,responseObject为json数据或者NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
// NSData转为NSString
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonStr = %@", jsonStr);
  • 重写description方法,也就是为字典或者数组添加一个分类
    当字典或者数组被打印的时候,系统自动调用重写的description方法不需要将该分类导入到任何类中。
    description方法有3个方法
    • descriptionWithLocale:indent:
    • descriptionWithLocale:
    • description
      这3个方法的调用顺序如下,
      descriptionWithLocale:indent:-> descriptionWithLocale:
      -> description
      官方文档中也说明了调用顺序

The returned NSString object contains the string representations of each of the dictionary’s entries. descriptionWithLocale:indent: obtains the string representation of a given key or value as follows:
If the object is an NSString object, it is used as is.
If the object responds to descriptionWithLocale:indent:, that method is invoked to obtain the object’s string representation.
If the object responds to descriptionWithLocale:, that method is invoked to obtain the object’s string representation.
If none of the above conditions is met, the object’s string representation is obtained by through its description property.

分类代码如下

#import "NSDictionary+Log.h"

@implementation NSDictionary (Log)

- (NSString *)descriptionWithLocale:(id)locale{
    
    NSMutableString *strM = [NSMutableString stringWithString:@"{\n"];
    
    [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        [strM appendFormat:@"\t%@ = %@;\n", key, obj];
    }];
    
    [strM appendString:@"}\n"];
    
    return strM;
}

@end

@implementation NSArray (Log)

- (NSString *)descriptionWithLocale:(id)locale{
    NSMutableString *strM = [NSMutableString stringWithString:@"(\n"];
    
    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        [strM appendFormat:@"\t%@,\n", obj];
    }];
    
    [strM appendString:@")"];
    
    return strM;
}

@end
  • 使用第三方插件(不推荐)
    FKConsole是一个用于在Xcode控制台显示中文的插件。地址直达这里
    详情请查看官方的文档,这里只贴出效果

你可能感兴趣的:(Xcode控制台中文问题)