根据NSDictionary中的值设置NSObject的属性



我想知道是否可以从NSDictionary设置NSObject的属性,而无需单独设置每个属性。

NSObject中的属性名称与NSDictionary中的密钥名称匹配。

有简单的方法吗?。

假设值的类型匹配,则要使用- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues NSNull值将被视为nil。

我写了一个小型库,它可以自动执行此操作,还可以处理日期转换https://github.com/aryaxt/OCMapper

只要所有键都与属性名称相同,它就会自动将NSDictionary转换为NSObject。

Customer *customer = [Customer objectFromDictionary:customerDictionary];
NSArray *customers = [Customer objectFromDictionary:listOfCustomersDictionary];

如果密钥和属性名称不相同,则可以编写映射

[mappingProvider mapFromDictionaryKey:@"dob" toPropertyKey:@"dateOfBearth" forClass:[Customer class]];

最新更新