Getting an NSArray of a single attribute from an NSArray

℡╲_俬逩灬. 提交于 2019-11-30 13:05:25

NSArray will handle this for you using KVC

NSArray *people ...;
NSArray *firstName = [people valueForKey:@"firstName"];

This will give you an array of the firstName values from each entry in the array

Check out the filterUsingPredicate: method in NSMutableArray, basically you create a NSPredicate object that will define how the array will be filtered.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-CJBDBHCB

This guide will give you an overview, and has a section for dealing with arrays.

You can also use block based enumeration:

NSArray *people;  // assumably has a bunch of people
NSMutableArray *firstNames = [NSMutableArray array];

[people enumerateObjectsUsingBlock: 
 ^(id obj, NSUInteger idx, BOOL*flag){
     // filter however you want...
     [firstNames addObject:[Person firstName]];
 }];

The benefit is it is fast and efficient if you have a bunch of people...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!