Zigglzworth
Zigglzworth

Reputation: 6813

Set the properties of an NSObject from the values in an NSDictionary

I would like to know if it is possible to set the properties of an NSObject from an NSDictionary without setting each one individually.

The property names in the NSObject match the key names in the NSDictionary.

Is there an easy way of doing this?.

Upvotes: 0

Views: 770

Answers (2)

aryaxt
aryaxt

Reputation: 77626

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]];

Upvotes: 1

BergQuester
BergQuester

Reputation: 6187

Assuming the types for the values match, you want to use - (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues NSNull values will be treated as nil.

Upvotes: 4

Related Questions