description

自我总结:

description方法:

1、在我看来主要是往出打印对象的时候,如果用系统默认的,那么就会打印出如下:<LYXApple: 0x100206930>

2、所有的OC对象都有该方法,因为description是NSObject类的一个实例方法

3、当程序员直接打印对象时,系统会输出该对象的“描述信息”,用于告诉外界该对象具有的状态信息,系统默认的,那么就会打印出如下:<LYXApple: 0x100206930>,所以我们如果需要自定义类能实现"自我描述"的功能,需要重写description方法。

下方演示:

程序代码:LYXApple.h

#import <Foundation/Foundation.h>

@interface LYXApple : NSObject
@property(nonatomic,assign)int weight;
@property(nonatomic,copy)NSString *name;
-(id)initWithWeight:(int)weight Name:(NSString *)name;
@end


程序代码:LYXApple.m

#import "LYXApple.h"

@implementation LYXApple
-(id)initWithWeight:(int)weight Name:(NSString *)name
{
    if (self = [super init]) {
        self.weight = weight;
        self.name = name;
    }
    return self;
}
//-(NSString *)description
//{
//    //返回一个字符串
//    return [NSString stringWithFormat:@"重%d斤,名字是%@",self.weight,self.name];
//}
@end


程序代码:main.m

#import <Foundation/Foundation.h>
#import "LYXApple.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        LYXApple *apple = [[LYXApple alloc]initWithWeight:18 Name:@"苹果"];
        NSLog(@"%@",apple);
        NSLog(@"%@",apple.name);
    }
    return 0;
}

如上代码,如果description方法注释掉的话,输出:

2016-02-15 22:11:41.780 description[1130:52272] <LYXApple: 0x100206930>
2016-02-15 22:11:41.782 description[1130:52272] 苹果
Program ended with exit code: 0

但是如果没有注释掉的话:

2016-02-15 22:47:50.310 description[1180:61418] 重18斤,名字是苹果
2016-02-15 22:47:50.311 description[1180:61418] 苹果
Program ended with exit code: 0
这就实现了重写,也就实现了description的作用:对该对象进行自我描述


你可能感兴趣的:(打印,nslog,description)