简体   繁体   English

将所有对象属性放入NSDictionary或NSArray中

[英]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? 有没有办法自动返回类中所有(公共)属性的NSDictionary? 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. 我知道我可以延迟实例化NSDictionary并在getter中手动用属性填充它。

It's easy to get an array of declared properties using the class_copyPropertyList and property_getName functions in the Objective-C runtime. 使用Objective-C运行时中的class_copyPropertyListproperty_getName函数很容易获得声明属性的数组。 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 . 您可以将此作为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. 我不确定你是怎么用NSDictionary做的,只是因为我不确定你对键值对的期望是什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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