- description 方法作用

自定义一个Person类

@interface Person : NSObject
{
    int _age;
    double _height;
    double _weight;
    NSString *_name;
    NSString *_tel;
    NSString *_email;
}


- (void)setAge:(int)age;
- (void)setHeigth:(double)height;
- (void)setWeight:(double)weight;
- (void)setName:(NSString *)name;
- (void)setTel:(NSString *)tel;
- (void)setEmail:(NSString *)email;

- (int)age;
- (double)height;
- (double)weight;
- (NSString *)name;
- (NSString *)tel;
- (NSString *)email;

 实现setter和getter,具体不详述了。

如果开发中想打印这个Person类创建出来的对象中的值通常情况是通过NSLog来答应,如下:

int main(int argc, const char * argv[]) {
    
    // 创建一个新对象并且赋值
    Person *p = [Person new];
    [p setAge:30];
    [p setName:@"lnj"];
    [p setHeigth:1.75];
    [p setWeight:65];
    [p setTel:@"13554499311"];
    [p setEmail:@"lnj@520it.com"];
    
  // 一般是通过这样打印,但是如果我们需要经常打印某个类创建出来的对象,每次这么写,就显得有点2了。解决办法就是通过重写这个类的 description这个对象方法来使得打印NSLog(@"%@",p),这样直接调用该方法,每次答应出来的就是我们想要的了。
// NSLog(@"age = %i, name = %@, height = %f, weight = %f, tel = %@, email = %@", [p age], [p name], [p height], [p weight], [p tel], [p email]); // %@是用来打印对象的, 其实%@的本质是用于打印字符串 // 只要利用%@打印某个对象, 系统内部默认就会调用父类的description方法 // 调用该方法, 该方法会返回一个字符串, 字符串的默认格式 <类的名称: 对象的地址> NSLog(@"person = %@", p); NSLog(@"%@", p); // class注意c是小写, 只要给类发送class消息, 就会返回当前类的类对象 // 1.获取Person对应的类对象 Class c = [Person class]; // 2.打印Person的类对象 NSLog(@"当前对象对应的类 = %@", c); NSLog(@"当前对象的地址 = %p", p); return 0; }

description方法

 注意点:

         在description方法中尽量不要使用self来获取成员变量

         因为如果你经常在description方法中使用self, 可能已不小心就写成了 %@, self

         如果在description方法中利用%@输出self会造成死循环,因为此时的self就是该类的对象,打印自己又会调用-description,无限循环了就。

         self == person实例对象

- (NSString *)description
{
    NSString *str = [NSString stringWithFormat:@"age = %i, name = %@, height = %f, weight = %f, tel = %@, email = %@", _age, _name, _height, _weight, _tel, _email];

    return str;
    
}
原文地址:https://www.cnblogs.com/XXxiaotaiyang/p/4990531.html