参考:xcode运行时修改array与dictionary中中文Unicode编码显示为中文字符问题
第一步:分别给NSArray
和NSDictionary
创建一个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);
}
}
网友评论