我正在努力学习客观-C中的反思。在如何转储类的属性列表(特别是here )方面,我发现了一些很好的信息,但我想知道是否可以使用反射设置属性值。
我有一个键(属性名)和值(所有NSString
s)的字典。我希望使用反射来获取属性,然后将其值设置为字典中的值。这个是可能的吗?还是我在做梦?
这与字典无关。我只是在用字典来发送这些值。
就像this question,但是对于目标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);
}
发布于 2014-08-28 00:25:35
目标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];
}
发布于 2014-08-28 00:44:20
NSKeyValueCoding
协议是NSObject
实现的(参见NSKeyValueCoding.h),它包含-setValuesForKeysWithDictionary:
方法。此方法完全采用您描述的字典类型,并设置接收者的适当属性(或ivars)。
这是绝对的反映;setValuesForKeysWithDictionary:
中的代码以您指定的名称访问属性,如果不存在setter方法,甚至会找到适当的ivar。
https://stackoverflow.com/questions/25538890
复制相似问题