views:

137

answers:

3

How to search an NSSet or NSArray for an object which has an specific value for an specific property?

Example: I have an NSSet with 20 objects, and every object has an type property. I want to get the first object which has [theObject.type isEqualToString:@"standard"].

I remember that it was possible to use predicates somehow for this kind of stuff, right?

+1  A: 
NSArray* results = [theFullArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.type LIKE[cd] %@", @"standard"]];
Jason Coco
+1  A: 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == %@", @"standard"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
id firstFoundObject = nil;
if ([filteredArray count] > 0) {
    firstFoundObject = [filteredArray objectAtIndex:0];
}

NB: The notion of the first found object in an NSSet makes no sense since the order of the objects in a set is undefined.

Ole Begemann
A: 

You can get the filtered array as Jason and Ole have described, but since you just want one object, I'd use - indexOfObjectPassingTest: (if it's in an array) or -objectPassingTest: (if it's in a set) and avoid creating the second array.

NSResponder