下午在测试一个语音 SDK 的时候,发现打印出来字典里的中文汉字都显示为 UTF-8 的字符,百度了一下解决办法,发现大都是用给 NSArray
和 NSDictionary
创建分类的方法解决的,但是很多文章可能是写的匆忙,或者是复制粘贴的,不够美观和一目了然。而且创建分类的方式,对比我以前用小码哥的一个类来说,多了一个 .h
文件,不够精简。所以就做个笔记,留作备用。
首先新建一个 OC 的 .m
文件,不知道怎么新建也可以直接,创建普通的 UIVIew
的类,把 .h
删除,把 .m
所有除注释以外代码删除,修改成如下文所示一致就好。
Objective-C1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #import <Foundation/Foundation.h>
@implementation NSDictionary (Log) - (NSString *)descriptionWithLocale:(id)locale { 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 { 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
|
GitHub 地址:NSDictionary+Log.m