OC基础--description方法

PS:经过之类重写description方法后,个人感觉有点像C#中的ToString();方法

一、description方法的作用:(输出所有的OC对象都用%@)

1、默认情况下(不重写description方法时)对象的输出信息是:<类名:  地址名> 例:<Person: 0x7fedc9c09720>

2、NSLog(@"Person对象:%@",p);--原理:会调用对象的-description方法,并且把-description方法返回的OC字符串输出的屏幕上

  请区分一下三者区别:

  1)直接输出某个对象的地址:

  Person *p = [Person new];

  NSLog(@"%p",p);

  2)输出指针变量的地址:NSLog(@"%p",&p);

  3)直接输出整个对象:NSLog(@"%@",p);

  默认输出是:<类名:  对象的内存地址>

  改变默认输出的方式:重写-description方法,返回自己想输出的内容

二、代码实例:

 1 #import <Foundation/Foundation.h>
 2 
 3 // Person的声明
 4 @interface Person : NSObject
 5 {
 6     int _age;
 7 }
 8 
 9 - (void) setAge:(int)age;
10 - (int) age;
11 
12 @end
13 
14 // Person的实现
15 @implementation Person
16 
17 - (void) setAge:(int)age
18 {
19     _age = age;
20 }
21 
22 - (int) age
23 {
24     return _age;
25 }
26 
27 //重写父类-description方法,利用NSString类的类方法stringWithFormat方法拼接字符串
28 //使得重写的-description方法返回自己想要的内容
29 - (NSString *) description
30 {
31     return [NSString stringWithFormat:@"age=%d", _age];
32 }
33 
34 @end
35 
36 
37 int main()
38 {
39     Person *p = [Person new];
40     [p setAge:29];
41     
42     // 输出所有的OC对象都用%@
43     // 默认情况下对象的输出信息:<Person: 0x7fedc9c09720>
44     // 类名 + 对象的内存地址
45     
46     // 给指针变量p所指向的对象发送一条-description消息
47     // 会调用对象的-description方法,并且把-description方法返回的OC字符串输出到屏幕上
48     NSLog(@"Person对象:%@", p);
49     /*
50     // 指针变量p的地址
51     NSLog(@"指针变量p的地址:%p", &p);
52     // 对象的地址
53     NSLog(@"这个Person对象的地址:%p", p);
54      */
55     return 0;
56 }
原文地址:https://www.cnblogs.com/gchlcc/p/5173384.html