ios NSLog 控制台 输出中文

作者: AmumuHandsome | 来源:发表于2018-07-13 15:17 被阅读97次

    在开发中,我们调试接口时最多的就是用NSLog 或者是打断点来po 数据,然而NSLog 输出的数据中,中文是UFT-8格式显示的,根本无法调试,所以为了解决这个问题,我在网上找了一些大神的做法,也尝试了几种方法,发现了一种比较好用的,今天就分享给大家。最终效果也很好

    image.png

    主要思路就是利用runtime 来替换掉系统的输出方法,然后将utf-8 转换成中文样式。

    第一步就是要分别创建NSArry 和 NSDictionary的categogry

    image.png

    然后在.m文件中复制如下代码即可大功告成

    代码如下

    + (void)load
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            zx_swizzleSelector([self class], @selector(descriptionWithLocale:indent:), @selector(zx_descriptionWithLocale:indent:));
        });
    }
    - (NSString *)zx_descriptionWithLocale:(id)locale indent:(NSUInteger)level
    {
        return [self stringByReplaceUnicode:[self zx_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 zx_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);
        }
    }
    

    大功告成!

    相关文章

      网友评论

      本文标题:ios NSLog 控制台 输出中文

      本文链接:https://www.haomeiwen.com/subject/ryojpftx.html