我有一个带有属性的类,我想从字典中设置值。
换句话说,我想自动化这个:
objectInstace.val1 = [dict objectForKey:@"val1"];
objectInstace.val2 = [dict objectForKey:@"val2"];
像这样的东西(伪代码):
for key, value in dict:
setattr(objectInstance, key, value)
我有一个带有属性的类,我想从字典中设置值。
换句话说,我想自动化这个:
objectInstace.val1 = [dict objectForKey:@"val1"];
objectInstace.val2 = [dict objectForKey:@"val2"];
像这样的东西(伪代码):
for key, value in dict:
setattr(objectInstance, key, value)
您可以使用键值编码方法setValuesForKeysWithDictionary:
。它正是你想要的。只是[someObject setValuesForKeysWithDictionary:propertiesDictionary]
。
好的,除非我遗漏了什么,否则为什么不创建如下方法:
setObjectProperties: (id) Object withValues:(NSDictionary *)dict
我从来没有这样做过,但这似乎应该有效:
对于key
字典中的每个:
NSString* setMethod = "set" + [key capitalizedString] + ":"; // This is pseudo-code.
SEL setSelector = NSSelectorFromString(setMethod);
[objectInstance performSelector:setSelector withObject:[dict objectForKey:key]];
(形成的代码setMethod
是伪代码并作为练习留下,因为 Obj-C 字符串操作太可怕了。)