在開發中我們經常需要在控制臺中打印出一些數據,以驗證我們代碼的正確性。一般我們的需求都是會打印出網絡請求的返回結果,返回的大部分都是json數據,但是直接輸出json數據時中文總會以原始碼文顯示,而不是正常顯示中文。
head = {
"is_auth" = "1.0";
"last_pack" = "1.0";
message = "\U64cd\U4f5c\U6210\U529f";
}
打印出的都是unicode編碼,非常不方便我們迅速的理解。此時其實打印的結果基本沒什么意義了。我們需要的是這樣
"head" : {
"is_auth" : "1.0",
"last_pack" : "1.0",
"message" : "操作成功",
}
解決辦法
- 使用代碼
直接將json數據或者字典轉換為NSData
// json數據或者NSDictionary轉為NSData,responseObject為json數據或者NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:responseObject options:NSJSONWritingPrettyPrinted error:nil];
// NSData轉為NSString
NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonStr = %@", jsonStr);
- 重寫description方法,也就是為字典或者數組添加一個分類
當字典或者數組被打印的時候,系統自動調用重寫的description方法不需要將該分類導入到任何類中。
description方法有3個方法- descriptionWithLocale:indent:
- descriptionWithLocale:
- description
這3個方法的調用順序如下,
descriptionWithLocale:indent:-> descriptionWithLocale:
-> description
官方文檔中也說明了調用順序
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是一個用于在Xcode控制臺顯示中文的插件。地址直達這里
詳情請查看官方的文檔,這里只貼出效果