在iOS開發中,經常需要查看數組中得元素是否是自己想要的,但是蘋果並沒有對直接打印數組中得中文作處理,直接打印就會出現一堆很討厭的東西,解決其實很簡單,就是需要通過為NSArray添加分類,重寫 - (NSString *)descriptionWithLocale:(id)locale方法即可
代碼如下:
#import "NSArray+Log.h" @implementation NSArray (Log) - (NSString *)descriptionWithLocale:(id)locale { NSMutableString *str = [NSMutableString stringWithFormat:@"%lu (\n", (unsigned long)self.count]; for (id obj in self) { [str appendFormat:@"\t%@, \n", obj]; } [str appendString:@")"]; return str; } @end
同理要解決NSDictionary亂碼問題,也需要為NSDictionary類添加一個分類,重寫 - (NSString *)descriptionWithLocale:(id)locale方法
代碼如下:
1 #import "NSDictionary+MyLog.h" 2 3 @implementation NSDictionary (MyLog) 4 5 6 - (NSString *)descriptionWithLocale:(id)locale 7 { 8 NSArray *allKeys = [self allKeys]; 9 NSMutableString *str = [[NSMutableString alloc] initWithFormat:@"{\t\n "]; 10 for (NSString *key in allKeys) { 11 id value= self[key]; 12 [str appendFormat:@"\t \"%@\" = %@,\n",key, value]; 13 } 14 [str appendString:@"}"]; 15 16 return str; 17 } 18 @end
