美文网首页
xcode运行时修改array与dictionary中中文Uni

xcode运行时修改array与dictionary中中文Uni

作者: 丿小七 | 来源:发表于2020-08-26 10:28 被阅读0次

参考:xcode运行时修改array与dictionary中中文Unicode编码显示为中文字符问题

第一步:分别给NSArrayNSDictionary创建一个Category类别:
第二步:类别.m文件里使用runtime机制在类的自调用函数load函数里将系统函数:

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

替换成自定义的descriptionWithLocale函数:

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

完整代码参考如下:



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

相关文章

网友评论

      本文标题:xcode运行时修改array与dictionary中中文Uni

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