Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 200
Haseeb Khan Avatar asked May 11 '11 18:05

Haseeb Khan


2 Answers

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

like image 81
Joshua Weinberg Avatar answered Oct 01 '22 06:10

Joshua Weinberg


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.

like image 29
avizzini Avatar answered Oct 01 '22 06:10

avizzini