ios NSLog 控制台 输出中文

在iOS开发中,我们调试接口时最多的就是用NSLog 或者是打断点来po 数据,然而NSLog 输出的数据中,中文是UFT-8格式显示的,

 

根本无法调试,所以为了解决这个问题,今天给大家推荐一个非常好的方法,主要思路就是利用objc/runtime运行时机制 来替换掉系统的控制台输出方法,然后将utf-8格式的字符转换成中文格式。

 一般情况下,我们在使用NSLog 和 %@ 输出某个对象时,就会调用这个对象的 description 方法,它的返回值就是 NSString 字符串类型,所以 description 默认实现返回的格式是 <类名: 对象的内存地址>,

在必要情况下,我们需要重写description方法以达到改变输出结果目的,覆盖description方法的默认实现。重写完description方法后,再调用NSLog(@”%@”,p)时输出结果不再是<类名: 内存地址>,而是返回的字符串。

注意:千万不要在 description 方法中同时使用 %@ 和 self,如果这样使用了,那么最终会造成程序死循环,原因是因为:如果使用了%@和self,代表要调用self的description方法,最终就是循环调用description方法

 

主要步骤:

第一步:分别给NSArray和NSDictionary创建一个Category类别:

第二步:类别.m文件里使用runtime机制在类的自调用函数load函数里将系统函数:

- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level

 替换成自定义的descriptionWithLocale函数:

- (NSString *)hd_descriptionWithLocale:(id)locale indent:(NSUInteger)level
+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hd_swizzleSelector([self class], @selector(descriptionWithLocale:indent:), @selector(hd_descriptionWithLocale:indent:));
    });
}

- (NSString *)hd_descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
    return [self stringByReplaceUnicode:[self hd_descriptionWithLocale:locale indent:level]];
}

 

第三步:然后在自定义的函数里对要输出到控制台的字符进行中文转义

- (NSString *)stringByReplaceUnicode:(NSString *)unicodeString
{
    NSMutableString *convertedString = [unicodeString mutableCopy];
    [convertedString replaceOccurrencesOfString:@"\\U" withString:@"\\u" options:0 range:NSMakeRange(0, convertedString.length)];
    CFStringRef transform = CFSTR("Any-Hex/Java");
    CFStringTransform((__bridge CFMutableStringRef)convertedString, NULL, transform, YES);
    
    return convertedString;
}
static inline void hd_swizzleSelector(Class theClass, SEL originalSelector, SEL swizzledSelector)
{
    Method originalMethod = class_getInstanceMethod(theClass, originalSelector);
    Method swizzledMethod = class_getInstanceMethod(theClass, swizzledSelector);
    
    BOOL didAddMethod =
    class_addMethod(theClass,
                    originalSelector,
                    method_getImplementation(swizzledMethod),
                    method_getTypeEncoding(swizzledMethod));
    
    if (didAddMethod) {
        class_replaceMethod(theClass,
                            swizzledSelector,
                            method_getImplementation(originalMethod),
                            method_getTypeEncoding(originalMethod));
    } else {
        method_exchangeImplementations(originalMethod, swizzledMethod);
    }
}

大功告成!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值