iOS开发那些事iOS开发

Xcode控制台中文问题

2016-07-19  本文已影响1146人  天天想念

在开发中我们经常需要在控制台中打印出一些数据,以验证我们代码的正确性。一般我们的需求都是会打印出网络请求的返回结果,返回的大部分都是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数据或者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);

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
上一篇下一篇

猜你喜欢

热点阅读