iOS 打印Unicode码转中文的解决办法

来源:互联网 发布:台达plc温度模块编程 编辑:程序博客网 时间:2024/06/06 10:06

1.前言

在开发中,我们经常会进行打印调试,但是有时候你会发现打印的内容并不是你想要的,因为它们是Unicode码(入下图),如何将打印信息转成中文呢,下面我给大家提供一种方法。

这里写图片描述

2.解决方法

我们一般打印的信息是数组信息和字典信息,它们的信息量比较多,与后台交互也多是转成这两种数据类型,我们分别创建它们的分类,然后重写 - (NSString *)descriptionWithLocale:(id)locale方法,在这里进行打印的调整,具体代码如下:

  • NSDictionary
#import "NSDictionary+DLog.h"@implementation NSDictionary (DLog)// log NSSet with UTF8// if not ,log will be \Uxxx- (NSString *)descriptionWithLocale:(id)locale{    if (![self count]) {        return @"";    }    NSString *tempStr1 =    [[self description] stringByReplacingOccurrencesOfString:@"\\u"                                                 withString:@"\\U"];    NSString *tempStr2 =    [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];    NSString *tempStr3 =    [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];    NSString *str =    [NSPropertyListSerialization propertyListWithData:tempData                                              options:NSPropertyListImmutable                                               format:NULL                                                error:NULL];    return str;}@end
  • NSArray
#import "NSArray+Dlog.h"@implementation NSArray (Dlog)-(NSString *)descriptionWithLocale:(id)locale{    NSMutableString *string = [NSMutableString string];    // 开头有个[    [string appendString:@"[\n"];    // 遍历所有的元素    [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {        [string appendFormat:@"\t%@,\n", obj];    }];    // 结尾有个]    [string appendString:@"]"];    // 查找最后一个逗号    NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];    if (range.location != NSNotFound)        [string deleteCharactersInRange:range];    return string;}@end
原创粉丝点击