开发者

Easiest way to populate array from custom class?

开发者 https://www.devze.com 2023-01-06 15:42 出处:网络
Say you have a class Person (with name, age, etc), and an array called PeopleArray which has several individual Person\'s.

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 ar开发者_开发知识库ray PeopleArray


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.


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号