Solve the problem of "garbled" (Unicode encoding) Chinese characters output by iOS NSDictionary

Simply define a dictionary and output the result:

NSDictionary *dic = @{
                      @"我是中文字符": @"223333",
                      @"aaa": @{
                                @"aaa": @"啦啦啦"
                              }
                      };
NSLog(@"%@", dic);

You will see such "garbled code", which is often encountered when debugging the server to return JSON results:

-02-25 19:23:40.346 XXXX[13273:417921] {
    
    
    aaa =     {
    
    
        aaa = "\U5566\U5566\U5566";
    };
    "\U6211\U662f\U4e2d\U6587\U5b57\U7b26" = 223333;
}

In fact, this is the representation method of Unicode encoding. By the way, let’s briefly understand Unicode encoding:

    \uxxxx这种格式是Unicode写法,表示一个字符,其中xxxx表示一个16进制数字,范围所0~65535. Unicode十六进制数只能包含数字0~9、大写字母A~F或者小写字母A~F。需要注意到是:Unicode的大小端问题,一般都是小端在前,例如 \u5c0f 表示汉语中的 ‘小’字,转换成10进制就是9215,所以在byte数组中应该是1592. (引自\u Unicode和汉字转化)

The solution is to re-encode the output string. In order to get rid of it once and for all, you can directly use Method swizzing to replace the original function. Here's how to do it:

Definition file NSDictionary+Unicode.m

@implementation NSDictionary (Unicode)

- (NSString*)my_description {
    NSString *desc = [self my_description];
    desc = [NSString stringWithCString:[desc cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding];
    return desc;
}

@end

First, import the JRSwizzle library into the project, add code in the didFinishLaunchingWithOptions method of AppDelegate.m, and replace the original description method:

[NSDictionary jr_swizzleMethod:@selector(description) withMethod:@selector(my_description) error:nil];

After completing the replacement, use the po command output during debugging to see the Chinese output:

(lldb) po dic
{
    aaa =     {
        aaa = "啦啦啦";
    };
    "我是中文字符" = 223333;
}

Remaining issues:
Using NSLog(@”%@”, dic); directly will still display garbled characters, and the reason is unclear. A temporary solution is to use NSLog(@”%@”, [dic description]);.

Guess you like

Origin blog.csdn.net/baidu_33298752/article/details/51647326