views:

1668

answers:

2

I have an NSArray formed with objects of a custom class. The class has 3 (city, state, zip) string properties. I would like to get all unique state values from the array.

I did read through the NSPredicate class but couldn't make much of how to use it in this case. The only examples I could find were for string operations.

Can someone please help me out?

+13  A: 

The totally simple one liner:

NSSet * uniqueStates = [NSSet setWithArray:[myArrayOfCustomObjects valueForKey:@"state"]];

The trick is the valueForKey: method of NSArray. That will iterate through your array (myArrayOfCustomObjects), call the -state method on each object, and build an array of the results. We then create an NSSet with the resulting array of states to remove duplicates.

Dave DeLong
Thanks a ton! You saved my day!
lostInTransit
+14  A: 

Take a look at keypaths. They are super powerful and I use them instead of NSPredicate classes most of the time. Here is how you would use them in your example...

NSArray *uniqueStates;
uniqueStates = [customObjects valueForKeyPath:@"@distinctUnionOfObjects.state"];

Note the use of valueForKeyPath instead of valueForKey.

Here is a more detailed/contrived example...

NSDictionary *arnold = [NSDictionary dictionaryWithObjectsAndKeys:@"arnold", @"name", @"califonria", @"state", nil];
NSDictionary *jimmy = [NSDictionary dictionaryWithObjectsAndKeys:@"jimmy", @"name", @"new york", @"state", nil];
NSDictionary *henry = [NSDictionary dictionaryWithObjectsAndKeys:@"henry", @"name", @"michigan", @"state", nil];
NSDictionary *woz = [NSDictionary dictionaryWithObjectsAndKeys:@"woz", @"name", @"califonria", @"state", nil];

NSArray *people = [NSArray arrayWithObjects:arnold, jimmy, henry, woz, nil];

NSLog(@"Unique States:\n %@", [people valueForKeyPath:@"@distinctUnionOfObjects.state"]);

// OUTPUT
// Unique States:
// "califonria",
// "michigan",
// "new york"
probablyCorey
+1 for use of distinctUnionOfObjects
Dave DeLong