description方法是NSObject类的一个实例方法,因此所有的Object-C对象都有description方法。description方法返回的永远是字符串。
对于一个Person类,如果没有重写description方法,NSLog(@“%@”,p),输出的是p的地址,而我们想要的效果是打印出person的成员变量,所以我们可以在Person类里重写description方法。
-(NSString *)description{
NSString * string = [NSString stringWithFormat:@"<Person: name = %@ age = %ld>",self.name,self.age];
return string;
}
另外一种方式创建分类,重写- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level;
方法
这是未做处理前的log,我们可以看到编辑器没有按照我们需要的方式打印中文
创建分类
注意:Xcode8.0以后,- (NSString *)descriptionWithLocale:(id)locale
方法不再可用,需要使用- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
NSArray+Log.h
#import <Foundation/Foundation.h>
@interface NSArray (Log)
@end
@interface NSDictionary (Log)
@end
NSArray+Log.m
#import "NSArray+Log.h"
@implementation NSArray (Log)
/**
* 输出正常NSArray的中文
*/
- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
NSMutableString *strM = [NSMutableString stringWithString:@"(\n"];
[self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[strM appendFormat:@"\t%@,\n", obj];
}];
[strM appendString:@")"];
return strM;
}
@end
@implementation NSDictionary (Log)
/**
* 输出正常NSDictionary的中文
*/
- (NSString *)descriptionWithLocale:(id)locale indent:(NSUInteger)level
{
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
在运行一下,如愿看到中文输入了