使用字典自动填充 Objective C 实例的所有属性
我有一个类,其中包含我想从字典中设置值的属性。
换句话说,我想自动化这个:
objectInstace.val1 = [dict objectForKey:@"val1"];
objectInstace.val2 = [dict objectForKey:@"val2"];
用这样的东西(伪代码):
for key, value in dict:
setattr(objectInstance, key, value)
I have a class with properties that I would like to set values from a dictionary.
In other words, I would like to automate this:
objectInstace.val1 = [dict objectForKey:@"val1"];
objectInstace.val2 = [dict objectForKey:@"val2"];
with something like this (pseudo code):
for key, value in dict:
setattr(objectInstance, key, value)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用键值编码方法
setValuesForKeysWithDictionary:
。它正是您想要的。只需[someObject setValuesForKeysWithDictionary:propertiesDictionary]
。You can use the Key-Value Coding method
setValuesForKeysWithDictionary:
. It does precisely what you want. Just[someObject setValuesForKeysWithDictionary:propertiesDictionary]
.好吧,除非我错过了一些东西,为什么不创建一个像这样的方法:
setObjectProperties: (id) Object withValues:(NSDictionary *)dict
ok unless I'm missing something why not create a method like:
setObjectProperties: (id) Object withValues:(NSDictionary *)dict
我从来没有这样做过,但这似乎应该有效:
对于字典中的每个
key
:(形成
setMethod
的代码是伪代码&左为一个练习,因为 Obj-C 字符串操作很糟糕。)I've never done this, but this seems like it should work:
For each
key
in the dictonary:(The code to form
setMethod
is pseudo-code & left as an exercise because Obj-C string manipulation is horrible.)