在開發(fā)中我們經(jīng)常需要在控制臺(tái)中打印出一些數(shù)據(jù),以驗(yàn)證我們代碼的正確性。一般我們的需求都是會(huì)打印出網(wǎng)絡(luò)請(qǐng)求的返回結(jié)果,返回的大部分都是json數(shù)據(jù),但是直接輸出json數(shù)據(jù)時(shí)中文總會(huì)以原始碼文顯示,而不是正常顯示中文。
head = {
"is_auth" = "1.0";
"last_pack" = "1.0";
message = "\U64cd\U4f5c\U6210\U529f";
}
打印出的都是unicode編碼,非常不方便我們迅速的理解。此時(shí)其實(shí)打印的結(jié)果基本沒什么意義了。我們需要的是這樣
"head" : {
"is_auth" : "1.0",
"last_pack" : "1.0",
"message" : "操作成功",
}
解決辦法
- 使用代碼
直接將json數(shù)據(jù)或者字典轉(zhuǎn)換為NSData
// json數(shù)據(jù)或者NSDictionary轉(zhuǎn)為NSData,responseObject為json數(shù)據(jù)或者NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
// NSData轉(zhuǎn)為NSString
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonStr = %@", jsonStr);
- 重寫description方法,也就是為字典或者數(shù)組添加一個(gè)分類
當(dāng)字典或者數(shù)組被打印的時(shí)候,系統(tǒng)自動(dòng)調(diào)用重寫的description方法不需要將該分類導(dǎo)入到任何類中。
description方法有3個(gè)方法- descriptionWithLocale:indent:
- descriptionWithLocale:
- description
這3個(gè)方法的調(diào)用順序如下,
descriptionWithLocale:indent:-> descriptionWithLocale:
-> description
官方文檔中也說明了調(diào)用順序
The returned NSString object contains the string representations of each of the dictionary’s entries. descriptionWithLocale:indent: obtains the string representation of a given key or value as follows:
If the object is an NSString object, it is used as is.
If the object responds to descriptionWithLocale:indent:, that method is invoked to obtain the object’s string representation.
If the object responds to descriptionWithLocale:, that method is invoked to obtain the object’s string representation.
If none of the above conditions is met, the object’s string representation is obtained by through its description property.
分類代碼如下
#import "NSDictionary+Log.h"
@implementation NSDictionary (Log)
- (NSString *)descriptionWithLocale:(id)locale{
NSMutableString *strM = [NSMutableString stringWithString:@"{\n"];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[strM appendFormat:@"\t%@ = %@;\n", key, obj];
}];
[strM appendString:@"}\n"];
return strM;
}
@end
@implementation NSArray (Log)
- (NSString *)descriptionWithLocale:(id)locale{
NSMutableString *strM = [NSMutableString stringWithString:@"(\n"];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[strM appendFormat:@"\t%@,\n", obj];
}];
[strM appendString:@")"];
return strM;
}
@end
- 使用第三方插件(不推薦)
FKConsole是一個(gè)用于在Xcode控制臺(tái)顯示中文的插件。地址直達(dá)這里
詳情請(qǐng)查看官方的文檔,這里只貼出效果