在调试程序时,经常需要打印并查看对象信息:我们经常会使用:
NSLog(@"object:%@",object)
在打印时,object会接收description消息:
NSString *object = @"pp";
NSLog(@"object:%@",object);
如果object是个字符串则会输出:
object:pp
但是如果我们在自定义的类中输出就会输出如下:
输入
DebugTest *debug = [[DebugTest alloc]init];
NSLog(@"object:%@",debug);
输出
object:<DebugTest: 0x7fe1c95a1320>
因此对于第二种则不是太有用在我们调试程序时:这里只是输出了类名以及对象的内存地址 为了实现与第一种相同的效果,我们可以采用复写description方法
假设我们自定义类如下:
#import "DebugTest.h"
@interface DebugTest()
@property (nonatomic,strong) NSArray *array;
@property (nonatomic,copy) NSString *name;
@end
@implementation DebugTest
-(instancetype)initWithName:(NSString *)name Array:(NSArray *)array{
if (self == [super init]) {
_name = name;
_array = array;
}
return self;
}
@end
该类的description方法和debugDescription方法可如下定义:
-(NSString *)description {
return [NSString stringWithFormat:@"%@--%@--%@",[self class],_name,_array];
}
-(NSString *)debugDescription{
return [NSString stringWithFormat:@"%@--%@--%@",[self class],_name,_array];
}
这时候输入:
DebugTest *debug = [[DebugTest alloc]initWithName:@"小李" Array:@[@"H",@"I"]];
NSLog(@"object:%@",debug);
输出:
object:DebugTest--小李--(
H,
I
)
因此可以实现和我们上面相同的效果,对于description和debugDescription的区别在于
description:从控制台输出NSLog
debugDescription:通过断点po打印
输出信息是一样的
因此如果想在调试时知道比较详细的信息需要实现debugDescription方法
例如:
(lldb) po debug
DebugTest--小李--(
H,
I
)
(lldb)