zoukankan      html  css  js  c++  java
  • 九: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会造成死循环

  • 相关阅读:
    XP下在控制面板和登录界面中隐藏用户方法
    DataGirdView 单元格限制内容输入参考(按键时的判断)
    VB.Net操作Excel
    VS扩展:标签左置 — productivity power tools
    使用VBS自动删除已经从FTP下载下来的文件
    VB.Net下ComboBox操作收集
    修改网卡IP信息的批处理文件
    VB.NET自定义控件 —— 添加控件自定义属性
    使用关键字对数组进行模糊查找;对一维字符串数组进行排序
    mysql多字段模糊查询
  • 原文地址:https://www.cnblogs.com/hissia/p/5437429.html
Copyright © 2011-2022 走看看