iphoneobjective-cios4iphone-sdk-3.0cocoa-design-patterns

Getting an NSArray of a single attribute from an NSArray


I am facing a very regular scenario.

I have an NSArray which has object of a custom type, say Person. The Person class has the attributes: firstName, lastName and age.

How can I get an NSArray containing only one attribute from the NSArray having Person objects?

Something like:

NSArray *people;
NSArray *firstNames = [people getArrayOfAttribute:@"firstName" andType:Person.Class]

I have a solution of writing a for loop and fill in the firstNames array but I don't want to do that.


Solution

  • 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