【OC梳理】description

2018-08-30  本文已影响20人  忠橙_g

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命令输出相同的结果。

上一篇 下一篇

猜你喜欢

热点阅读