2

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0
NSMutableArray *nameArray = [NSMutableArray arrayWithCapacity:0]; // autoreleased, so no leak
for (Person *peep in peopleArray) {  
    [nameArray addObject:peep.name]; // assumes you made name a property  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.