简体   繁体   中英

Put all object properties into an NSDictionary or NSArray

Is there a way to automatically return an NSDictionary of all the (public) properties in a class? You can assume all properties are property lists and that I don't want to just hand over a pointer to the class itself. Any existing magic that can pull this off?

I know I can lazy instantiate an NSDictionary and manually fill it with properties in the getter.

It's easy to get an array of declared properties using the class_copyPropertyList and property_getName functions in the Objective-C runtime. Here's one such implementation:

- (NSArray *)properties
{
    NSMutableArray *propList = [NSMutableArray array];
    unsigned int numProps = 0;
    unsigned int i = 0;

    objc_property_t *props = class_copyPropertyList([TestClass class], &numProps);
    for (i = 0; i < numProps; i++) {
        NSString *prop = [NSString stringWithUTF8String:property_getName(props[i])];
        [propList addObject:prop];
    }

    return [[propList copy] autorelease];
}

You could add this as a method in a category on NSObject . Here's a full code listing that can be compiled that demonstrates this.

I'm not sure how'd you do it with an NSDictionary , only because I'm not sure what you expect the key-value pairs to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM