I have an array of dictionaries. I would like to extract an array with all the elements of one particular key of the dictionaries in the original array. Can this be done without enumeration?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes, use the NSArray -valueForKey:
method.
NSArray *extracted = [sourceArray valueForKey:@"a key"];
回答2:
Yes, just use Key-Value Coding to ask for the values of the key:
NSArray* names = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:
@"Joe",@"firstname",
@"Bloggs",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Simon",@"firstname",
@"Templar",@"surname",
nil],
[NSDictionary dictionaryWithObjectsAndKeys:
@"Amelia",@"firstname",
@"Pond",@"surname",
nil],
nil];
//use KVC to get the names
NSArray* firstNames = [names valueForKey:@"firstname"];
NSLog(@"first names: %@",firstNames);