在开发过程中为了方便调试一般会将请求数据参数或者结果打印在控制台上,使用系统默认的方法调用的是description方法,所以打印出来的参数中包含中文控制台中显示的是unicode编码如图:
解决方案.可以写一个NSObject的分类NSObject+Log 内部实现如下:
import <Foundation/Foundation.h>
@interface NSObject (Log)
@end
import "NSObject+Log.h"
@implementation NSObject (Log)
@end
@implementation NSDictionary (Log)
-
(NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level{
NSMutableString *string = [NSMutableString string];
// 开头有个{
[string appendString:@"{\n"];// 遍历所有的键值对
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[string appendFormat:@"\t%@", key];
[string appendString:@" : "];
[string appendFormat:@"%@,\n", obj];
}];// 结尾有个}
[string appendString:@"}"];// 删除最后一个逗号
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
if (range.location != NSNotFound)
[string deleteCharactersInRange:range];return string;
}
@end
@implementation NSArray (Log)
-
(NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level{
NSMutableString *string = [NSMutableString string];
// 开头有个[
[string appendString:@"[\n"];// 遍历所有的元素
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[string appendFormat:@"\t%@,\n", obj];
}];// 结尾有个]
[string appendString:@"]"];// 删除最后一个逗号
NSRange range = [string rangeOfString:@"," options:NSBackwardsSearch];
if (range.location != NSNotFound)
[string deleteCharactersInRange:range];return string;
}
@end
打印效果如下:
在Xcode8.0以前我一直是重写的
- (NSString *)descriptionWithLocale:(id)locale 方法
但是当XCode升级8.0以后这个方法不是每次打印的时候都会调用所以导致有些打印还是unicode编码 修改成 - (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
解决这个bug