views:

50

answers:

3

Say you have a class Person (with name, age, etc), and an array called PeopleArray which has several individual Person's.

What's the easiest way of extracting each Person's name (for instance) and putting it into an array. Psuedocode is:

nameArray = every Person's name, from the array PeopleArray
+1  A: 
NSMutableArray *nameArray = [[NSMutableArray alloc] init];
for (Person *person in peopleArray) {
    [nameArray addObject:person.name];
}
Douwe Maan
+4  A: 

Edit: I've found a better solution than the answers I previously posted

NSArray* names = [peopleArray valueForKey: @"name"];

Sends -name to every element of peopleArray and builds a new array of the results

Documentation

One way, use fast enumeration:

NSMutableArray* nameArray = [[NSMutableArray alloc] init];
for (Person* person in peopleArray)
{
    [nameArray addObject: [person name]];

}

Another way, to distinguish my answer from the identical one posted just before mine :-)

Create a method on Person called addNameToArray: and use makeObjectsPerformSelector:

// Person.m

-(void) addNameToArray: (id) aMutableArray
{
    [aMutableArray addObject: [self name]];
}

// where you want to add the names

NSMutableArray* nameArray = [[NSMutableArray alloc] init];
[peopleArray makeObjectsPerformSelector: @selector(addNameToArray:) withObject: nameArray];

Disappointingly there seems to be no equivalent to the map function.

JeremyP
That's pretty cool! Always something new to learn on SO.
willc2
A: 
NSMutableArray *nameArray = [NSMutableArray arrayWithCapacity:0]; // autoreleased, so no leak
for (Person *peep in peopleArray) {  
    [nameArray addObject:peep.name]; // assumes you made name a property  
}
willc2