Create an NSObject from NSDictionary in objective-c

I would like to assign each element from the dictionary to my object using the "for ... in" loop

I have an NSDictionary like this:

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

And I have an NSObject with a variable:

 NSString *user_id; NSString *user_name 

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

 for (NSString *param in userDictionary) { } 

How can i do this?

Thanks,

+4
source share
2 answers

Take a look at the NSObject class method:

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

For instance:

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

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

It automatically converts NSDictionary to NSObject if all keys match property names.

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

If the names of the keys and properties do not match, you can write a mapping

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

Source: https://habr.com/ru/post/1397289/


All Articles