• 九:description方法


    一、基本含义

    1、当用%@打印类或对象时候,系统内部默认就会调用 description方法,拿到返回值进行输出,默认输出的是返回类名和对象的内存地址。

    其实%@的本质是用于打印字符串.

    调用该方法, 该方法会返回一个字符串, 字符串的默认格式 <类的名称: 对象的地址>

    2、代码:

     1 #import <Foundation/Foundation.h>
     2 @interface Animal: NSObject
     3 /** 颜色 */
     4 @property (strong, nonatomic)NSString *color;
     5 @end
     6 @implementation Animal
     7 @end
     8 
     9 int main(int argc, const char * argv[]) {
    10     @autoreleasepool {
    11         Animal *a = [[Animal alloc] init];
    12         a.color = @"green";
    13         NSLog(@"%@",a);  //打印对象a 
    14     }
    15     return 0;
    16 }

    输出结果:

    1 2016-04-27 07:55:42.250 description[4955:864017] <Animal: 0x1006000a0>
    2 Program ended with exit code: 0

    二、重写description

    description方法的默认实现是返回类名和对象的内存地址,这样的话,使用NSLog输出OC对象,意义就不是很大,因为我们并不关心对象的内存地址,比较关心的是对象内部的一些成变量的值。因此,会经常重写description方法,返回对象的属性,覆盖description方法的默认实现。

    代码:

    #import <Foundation/Foundation.h>
    @interface Animal: NSObject
    /** 颜色 */
    @property (strong, nonatomic)NSString *color;
    @end
    @implementation Animal
    - (NSString *)description
    {
        return [NSString stringWithFormat:@"color:%@",_color]; //此处的_color决不能写成self,否则会造成死循环
    }
    @end
    
    int main(int argc, const char * argv[]) {
        @autoreleasepool {
            Animal *a = [[Animal alloc] init];
            a.color = @"green";
            NSLog(@"%@",a);  //这时候打印的就是对象的属性
        }
        return 0;
    }

    输出结果:

    2016-04-27 08:09:42.105 description[4983:875363] color:green
    Program ended with exit code: 0

    注意:如果在description方法中利用%@输出self会造成死循环

  • 相关阅读:
    windows XP 下的DTRACE 跟踪 学习
    copy to tmp table
    快麦
    SQL SERVER BOOK
    启锐电子面单驱动
    grep---find
    mysql中kill掉所有锁表的进程
    sqlserverinternals.com
    从顺序随机I/O原理来讨论MYSQL MRR NLJ BNL BKA
    解析MYSQL BINLOG二进制格式
  • 原文地址:https://www.cnblogs.com/hissia/p/5437429.html
Copyright © 2020-2023  润新知