Create an array of single ivar from array objects with multiple ivars

If I have a class with two properties "a" and "b", and I have an array of these class instances. What is the best way to create an array of only "a" elements.

+3
source share
2 answers

The easiest way is Keyword Coding :

[yourArray valueForKey:@"a"];
+2
source

Just iterate over instances of the class and create a new array:

// Presuming some NSArray * classInstances of type MyClass
NSMutableArray * aProperties = [[[NSMutableArray alloc] 
                                 initWithCapacity:[classInstances count]] 
                                autorelease];
for(MyClass * myInstance in classInstances) {
    [aProperties addObject:[myInstance a]];
}

If your class matches the keyword encoding for a, you can also specify an array for the values ​​directly:

NSArray * aProperties = [classInstances valueForKey:@"a"];
+2
source

All Articles