问题
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