description的使用

description基本概念

  • NSLog(@”%@”, objectA);这会自动调用objectA的descriptong方法来输出ObjectA的描述信息.
  • descriptong方法默认返回对象的描述信息(默认实现是返回类名和对象的内存地址)
  • description方法是基类NSObject 所带的方法,因为其默认实现是返回类名和对象的内存地址, 这样的话,使用NSLog输出OC对象,意义就不是很大,因为我们并不关心对象的内存地址,比较关心的是对象内部的一些成变量的值。因此,会经常重写description方法,覆盖description方法 的默认实现

description重写的方法

  • 对象方法:当使用NSLog输出该类的实例对象的时候调用
  • 类方法:当使用NSLog输出该类的类对象的时候调用
    例如:
    Person *person = [[Person alloc] init];   
    person.name = @"yan";
    NSLog(@"%@",person);
  • 没有重写description:
    打印结果: <Person: 0x7f8ba300bfd0>
  • 重写description:
 - (NSString *)description{
    return [NSString stringWithFormat:@"name = %@",self.name];
 }
  打印结果:name = yan

description陷阱

  • 千万不要在description方法中同时使用%@和self,下面的写法是错误的
 - (NSString *)description {
      return [NSString stringWithFormat:@”%@”, self];
}

同时使用了%@和self,代表要调用self的description方法,因此最终会导致程序陷入死循环,循环调用description方法.

  • 当该方法使用NSLog(“%@”,self) 时候, 系统做了相关的优化,循坏调用3次后就会自动退出

代码实现:

下面这段代码我写在了NSObject的分类中了并做了相应的优化

@implementation NSObject (Category)

static NSMutableDictionary *modelsDescription = nil;
+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        modelsDescription = [NSMutableDictionary dictionary];
    });
}
- (NSString *)description {
    NSMutableString *str = [NSMutableString string];
    NSString *className = NSStringFromClass([self class]);
    NSMutableDictionary *value = modelsDescription[className];
    // 避免重复调用propertiesToDictionary
    if (value) {
        [value enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [str appendFormat:@"%@ = %@\n", key, obj];
        }];
    }else{
        
        NSDictionary *dict = [self propertiesToDictionary];
        [modelsDescription setObject: dict forKey:className] ;
        [dict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [str appendFormat:@"%@ = %@\n", key, obj];
        }];
    }
    return str;
}
- (NSMutableDictionary *)propertiesToDictionary {
    // 用以存储属性(key)及其值(value)
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
    // 获取当前类对象类型
    Class cls = [self class];
    // 获取类对象的成员变量列表,ivarsCount为成员个数
    uint ivarsCount = 0;
    Ivar *ivars = class_copyIvarList(cls, &ivarsCount);
    // 遍历成员变量列表,其中每个变量为Ivar类型的结构体
    const Ivar *ivarsEnd = ivars + ivarsCount;
    for (const Ivar *ivarsBegin = ivars; ivarsBegin < ivarsEnd; ivarsBegin++) {
        Ivar const ivar = *ivarsBegin;
        // 获取变量名
        NSString *key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        /*
         若此变量声明为属性,则变量名带下划线前缀'_'
         比如 @property (nonatomic, copy) NSString *name;则 key = _name;
         为方便查看属性变量,在此特殊处理掉下划线前缀
         */
        if ([key hasPrefix:@"_"]) key = [key substringFromIndex:1];
        // 获取变量值
        id value = [self valueForKey:key];
        // 处理属性未赋值属性,将其转换为null,若为nil,插入将导致程序异常
        [dictionary setObject:value ? value : [NSNull null]
                       forKey:key];
    }
    if (ivars) {
        free(ivars);
    }
    return dictionary;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容