Getting an NSArray of a single attribute from an NSArray
Asked Answered
F

3

9

I am facing a very regular scenario.

I have an NSArray which has object of a custom type, say Person. The Person class has the attributes: firstName, lastName and age.

How can I get an NSArray containing only one attribute from the NSArray having Person objects?

Something like:

NSArray *people;
NSArray *firstNames = [people getArrayOfAttribute:@"firstName" andType:Person.Class]

I have a solution of writing a for loop and fill in the firstNames array but I don't want to do that.

Furfuran answered 11/5, 2011 at 18:14 Comment(3)
Is it something similar to an array of dictionaryRolland
Why don't you want to loop the array?Invulnerable
I don't want to loop the array manually just to save the lines of code and implement the stuff I am working on in an elegant manner.Furfuran
S
22

NSArray will handle this for you using KVC

NSArray *people ...;
NSArray *firstName = [people valueForKey:@"firstName"];

This will give you an array of the firstName values from each entry in the array

Shack answered 11/5, 2011 at 18:25 Comment(0)
A
1

Check out the filterUsingPredicate: method in NSMutableArray, basically you create a NSPredicate object that will define how the array will be filtered.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Predicates/Articles/pUsing.html#//apple_ref/doc/uid/TP40001794-CJBDBHCB

This guide will give you an overview, and has a section for dealing with arrays.

Aplanospore answered 11/5, 2011 at 18:22 Comment(2)
+1: This is correct, but unless its a massive array, just using a for loop will work, and without the hassle of using Predicates.Dilettantism
His question isn't about filtering the array, its about creating an array from one key of the values in the array.Shack
E
1

You can also use block based enumeration:

NSArray *people;  // assumably has a bunch of people
NSMutableArray *firstNames = [NSMutableArray array];

[people enumerateObjectsUsingBlock: 
 ^(id obj, NSUInteger idx, BOOL*flag){
     // filter however you want...
     [firstNames addObject:[Person firstName]];
 }];

The benefit is it is fast and efficient if you have a bunch of people...

Elwina answered 11/5, 2011 at 21:10 Comment(1)
Cool. I forgot that KVC would do this. Thanks for reminding me. (Voted)Prudy

© 2022 - 2024 — McMap. All rights reserved.