I have data from JSON response that I am transferring to an array as sh开发者_如何学编程own below
originalPerson.firstname = [memberData valueForKey:@"firstname"];
originalPerson.lastname = [memberData valueForKey:@"lastname"];
originalPerson.address1 = [memberData valueForKey:@"address1"];
Is there a way to handle this in a loop rather than typing each line out? TIA
If the class of the instance originalPerson is key-value coding (KVC) compliant, you could use something like
for (NSString* key in [NSArray arrayWithObjects:@"firstname", @"lastname", @"address1", nil]) {
[originalPerson setValue:[memberData valueForKey:key] forKey:key];
}
or even
for (NSString* key in [memberData allKeys]) {
[originalPerson setValue:[memberData valueForKey:key] forKey:key];
}
if member data is a dictionary and you're sure (or check that) originalPerson has the corresponding properties. I don't know how you are parsing your JSON but I recomend SBJSON for objective C.
You can also do
[originalPerson setValuesForKeysWithDictionary:memberData]
be careful that memberData
should not contain any key that does not correspond to an attribute of originalPerson
, or the runtime will raise an exception.
精彩评论