description和debugDescription方法

代码:

#import <Foundation/Foundation.h>

/******************************
 * Person类
 ******************************/
@interface Person : NSObject

@end

@implementation Person

- (NSString *)description {
    return @"-[Person description]";
}

- (NSString *)debugDescription {
    return @"-[Person debugDescription]";
}

@end

/******************************
 * main函数
 ******************************/
int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *p = [[Person alloc] init];
        
        // 系统默认实现
        // NSLog输出
        // <Person: 0x7f9bc6800600>
        // po p输出
        // <Person: 0x7f9033805340>
        NSLog(@"%@", p);
        
        // 重写description和debugDescription方法后
        // NSLog输出
        // -[Person description]
        // po p输出
        // -[Person debugDescription]
    }
    return 0;
}

说明:

当通过NSLog函数打印一个对象时,其输出结果就是该对象的description方法的返回值。

当在LLDB中,通过诸如po命令打印一个对象时,其输出结果就是该对象的debugDescription方法的返回值。

debugDescription方法的默认实现就是直接返回description方法的返回值。

原文地址:https://www.cnblogs.com/xwoder/p/5080305.html