Create NSObject from NSDictionary in objective-c

夙愿已清 提交于 2019-12-10 16:53:53

问题


I would like to assign each item from a dictionary into my object using a "for...in" loop

I have a NSDictionary like that :

{"user_id" : "1", "user_name" : "John"}

And I have an NSObject with variable :

NSString *user_id;
NSString *user_name

With a for in loop, I want to assign each item from my NSDictionary in my NSObject

for (NSString *param in userDictionary) {

}

How I can do that ?

Thanks,


回答1:


Have a look at the NSObject class method:

- (void)setValue:(id)value forKey:(NSString *)key;

For example:

[userDictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
    [myObject setValue:obj forKey:(NSString *)key];
}];



回答2:


I wrote a small library that automates this, it also handles conversion of dates https://github.com/aryaxt/OCMapper

It automatically converts NSDictionary to NSObject as long as all keys are the same as property names.

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

if the key and property names are not the same you can write mapping

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


来源:https://stackoverflow.com/questions/9349692/create-nsobject-from-nsdictionary-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!