用Xcode开发时,有时需要跟踪对象的详细信息内容,但是有时 对象的属性中有数组并且数组的内容为中文时,用NSLog输出对象时,数组中的中文无法显示会无法显示。
例如:
//person类 #import <Foundation/Foundation.h> @interface Person : NSObject @property (nonatomic,copy) NSString *name; //兴趣属性,为数组 @property (nonatomic,strong) NSArray *interests; @end #import "Person.h" @implementation Person - (NSString *)description { return [NSString stringWithFormat:@"name = %@,interests = %@",_name,_interests]; } @end
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { Person *p = [[Person alloc]init]; p.name = @"王二麻子"; p.interests = @[@"打架",@"嫖娼",@"贩毒"]; //输出p对象的内容 NSLog(@"%@",p); } return 0; }
输出结果:
2014-05-25 20:24:14.887 显示中文[1064:303] name = 王二麻子,interests = (
"U6253U67b6",
"U5ad6U5a3c",
"U8d29U6bd2"
)
Program ended with exit code: -1
要想显示中文,需要对数组添加分类如下:
1 #import "NSArray+Log.h" 2 3 @implementation NSArray (Log) 4 5 - (NSString *)descriptionWithLocale:(id)locale 6 { 7 // 遍历数组中的所有内容,将内容拼接成一个新的字符串返回 8 NSMutableString *strM = [NSMutableString string]; 9 10 [strM appendString:@"( "]; 11 12 // 遍历数组,self就是当前的数组 13 for (id obj in self) { 14 // 在拼接字符串时,会调用obj的description方法 15 [strM appendFormat:@" %@, ", obj]; 16 } 17 18 [strM appendString:@")"]; 19 20 return strM; 21 } 22 23 @end
再次运行结果:
2014-05-25 20:33:45.259 显示中文[1116:303] name = 王二麻子,interests = (
打架,
嫖娼,
贩毒,
)