美文网首页
【OC梳理】description

【OC梳理】description

作者: 忠橙_g | 来源:发表于2018-08-30 17:34 被阅读20次

    iOS中,使用NSLog输出NSObject对象时常使用%@修饰,其输出结果一般类似:

     <Object: 0x1234567890>
    

    这样的输出并没什么鸟用,如果想让输出的结果更加清晰,可以在子类中重写- (NSString *)description;方法,返回想要输出的信息,例如:

    // ...
    @property (nonatomic, copy, readonly) NSString * name;
    @property (nonatomic, copy, readonly) NSString * address;
    // ...
    - (NSString *)description{
        return [NSString stringWithFormat:@"<%@ : %p, \"%@ %@\">", [self class], self, _name, _address];
    }
    

    使用NSLog输出该对象:

    ... <Object: 0x123456789, "_name _address">
    

    或者我们可以将属性放到NSDictionary中,让输出更加清晰:

    // ...
    - (NSString *)description{
        return  [NSString stringWithFormat:@“%@-> %p: \n%@”, [self class], self, @{@"name":_name,
                        @"address":_address}];
    }
    

    输出结果为:

    Object:-> 0x123456789:
    {
        name = _name;
        address = _address;
    }
    

    如果我们更懒一点,使用runtime遍历属性进行输出:

    // ...
    #import <objc/runtime.h>
    // ...
    - (NSString *)description{
        unsigned int count ,i;
        objc_property_t *propertyArray = class_copyPropertyList([self class], &count);
        NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
        for (i = 0; i < count; i++) {
            objc_property_t property = propertyArray[i];
            NSString *proKey = [NSString stringWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            id proValue = [self valueForKey:proKey];
            
            if (proValue) {
                [mutDic setObject:proValue forKey:proKey];
            } else {
                [mutDic setObject:@"" forKey:proKey];
            }
        }
        free(propertyArray);
        return  [NSString stringWithFormat:@"%@: %p, \n%@", [self class], self, mutDic];
    }
    

    同时,我们在debugDescription中实现相同的代码,以便于调试时使用po命令输出相同的结果。

    相关文章

      网友评论

          本文标题:【OC梳理】description

          本文链接:https://www.haomeiwen.com/subject/jzrdwftx.html