解决输出字典/数组 打印编码问题

来源:互联网 发布:4g移动网络接入点设置 编辑:程序博客网 时间:2024/05/22 08:22

在我们直接使用系统打印字典是,输出的汉字会变为Unicode编码,为了解决这个问题,我们需要重写系统的方法

首先我们创建一个NSDictionary 的分类 Decription

然后重写load方法,这load方法实现以下内容

+(void)load

{

    [super load];

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        Class class = [selfclass];

        SEL originalSelector =@selector(descriptionWithLocale:);

        SEL swizzledSelector =@selector(zwl_descriptionWithLocale:);

        Method originalMethod =class_getInstanceMethod(class, originalSelector);

        Method swizzledMethod =class_getInstanceMethod(class, swizzledSelector);

        method_exchangeImplementations(originalMethod, swizzledMethod);

    });

}


接着实现我们自己定义的方法

-(NSString *)zwl_descriptionWithLocale:(id)locale{

    NSString *dataString =nil;

    @try {

        NSData *data = [NSJSONSerializationdataWithJSONObject:selfoptions:NSJSONWritingPrettyPrintederror:nil];

        dataString = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    } @catch (NSException *exception) {

        dataString = nil;

    } @finally {

        if (dataString) {

            return dataString;

        }

        return [self zwl_descriptionWithLocale:locale];

    }

}

这样,我们通过使用runtime交换与系统的方法,得到了我们想要的结果。

因为这次分享的内容过少,在这里我就不贴出工程的下载地址了。



0 0
原创粉丝点击