6

我想重写我的对象的描述方法,以便能够打印我声明的所有属性的值。我知道我可以通过将所有值一个一个地附加到彼此来做到这一点,但是如果您有很多属性,有时这会很耗时。

我想知道是否有一种简单的方法可以通过 Objective-C 的运行时功能获得帮助?

4

1 回答 1

6

你试过这个解决方案吗?

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface NSObject (PropertyListing)

// aps suffix to avoid namespace collsion
//   ...for Andrew Paul Sardone
- (NSDictionary *)properties_aps;

@end

@implementation NSObject (PropertyListing)

- (NSDictionary *)properties_aps {
    NSMutableDictionary *props = [NSMutableDictionary dictionary];
    unsigned int outCount, i;
    objc_property_t *properties = class_copyPropertyList([self class], &outCount);
    for (i = 0; i < outCount; i++) {
        objc_property_t property = properties[i];
        NSString *propertyName = [[[NSString alloc] initWithCString:property_getName(property)] autorelease];
        id propertyValue = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) [props setObject:propertyValue forKey:propertyName];
    }
    free(properties);
    return props;
}

@end
于 2012-12-14T15:17:13.763 回答