使用反射设置Objective-C类的属性值

Pat*_*cia 5 reflection objective-c

我正在尝试学习Objective-C中的反射.我已经找到了一些关于如何转储类的属性列表的重要信息,特别是在这里,但我想知道是否可以使用反射设置属性的值.

我有一个键(属性名称)和值(所有NSStrings)的字典.我想使用Reflection获取属性,然后将其值设置为我的字典中的值.这可能吗?还是我在做梦?

这与字典无关.我只是使用字典发送值.

这个问题,但对于目标C.

- (void)populateProperty:(NSString *)value
{
    Class clazz = [self class];
    u_int count;

    objc_property_t* properties = class_copyPropertyList(clazz, &count);
    for (int i = 0; i < count ; i++)
    {
        const char* propertyName = property_getName(properties[i]);
        NSString *prop = [NSString  stringWithCString:propertyName encoding:NSUTF8StringEncoding]];
        // Here I have found my prop
        // How do I populate it with value passed in?
    }
    free(properties);

}
Run Code Online (Sandbox Code Playgroud)

Fru*_*eek 13

Objective C属性自动符合NSKeyValueCoding协议.您可以使用setValue:forKey:通过字符串属性名称设置任何属性值.

NSDictionary * objectProperties = @{@"propertyName" : @"A value for property name",
                                    @"anotherPropertyName" : @"MOAR VALUE"};

//Assuming class has properties propertyName and anotherPropertyName
NSObject * object = [[NSObject alloc] init];

for (NSString * propertyName in objectProperties.allKeys)
{
    NSString * propertyValue = [objectProperties valueForKey:propertyName];

    [object setValue:propertyValue
              forKey:propertyName];
}
Run Code Online (Sandbox Code Playgroud)

  • @Lucy [`setValue:forKey:`](https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/Protocols/NSKeyValueCoding_Protocol/Reference/Reference.html#//apple_ref/doc/uid/20000471-BABEHECF)是`NSKeyValueCoding`协议的一部分,`NSObject`符合.它与字典无关; 你在考虑`setObject:forKey:`,它是`NSMutableDictionary`的一个方法. (3认同)