Creating an array from the properties of objects in another array

Is there any convenient way to take an array / set of objects and create a new array / set containing some property of each element in the first array?

For example, an array contains Car objects. I need an array of licensePlates where every car has an NSObject car.licensePlate.

Currently, I just iterate over the first array, adding objects to my mutable result array, but wondered if there was an instance creation method for it (documents checked for NSArray).

+56
objective-c nsarray nsset
Mar 27 '12 at 13:48
source share
1 answer

This returns an array containing the licensePlate value from each element of the myCars array:

 NSArray *licensePlates = [myCars valueForKeyPath:@"licensePlate"] 

If you want only unique elements (for example), you can do something like this:

 NSArray *licensePlates = [myCars valueForKeyPath:@"@distinctUnionOfObjects.licensePlate"]; 

For more features, see the Collection Operators documentation in the Key- Value Encoding Programming Guide .

+112
Mar 27 '12 at 13:50
source share



All Articles