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

How to find an NSSet or NSArray for an object that has a specific value for a specific property?

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

I remember that you could use predicates somehow for this kind of thing, right?

+48
objective-c iphone nsarray nspredicate nsset
Jun 19 '10 at 17:16
source share
4 answers
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == %@", @"standard"]; NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate]; id firstFoundObject = nil; firstFoundObject = filteredArray.count > 0 ? filteredArray.firstObject : nil; 

NB: the concept of the first found object in NSSet does not make sense, since the order of the objects in the set is undefined.

+76
Jun 19 '10 at 17:23
source share
— -

You can get a filtered array, as described by Jason and Ole, but since you only need one object, I would use - indexOfObjectPassingTest: (if it is in the array) or -objectPassingTest: (if it is in the set) and do not create a second array.

+17
Jun 20 '10 at 21:19
source share

As a rule, I use indexOfObjectPassingTest: since it is more convenient for me to express my test in Objective-C, rather than NSPredicate syntax. Here is a simple example (imagine that integerValue was actually a property):

 NSArray *array = @[@0,@1,@2,@3]; NSUInteger indexOfTwo = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { return ([(NSNumber *)obj integerValue] == 2); }]; NSUInteger indexOfFour = [array indexOfObjectPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) { return ([(NSNumber *)obj integerValue] == 4); }]; BOOL hasTwo = (indexOfTwo != NSNotFound); BOOL hasFour = (indexOfFour != NSNotFound); NSLog(@"hasTwo: %@ (index was %d)", hasTwo ? @"YES" : @"NO", indexOfTwo); NSLog(@"hasFour: %@ (index was %d)", hasFour ? @"YES" : @"NO", indexOfFour); 

The output of this code is:

 hasTwo: YES (index was 2) hasFour: NO (index was 2147483647) 
+13
Aug 16 '13 at 14:25
source share
 NSArray* results = [theFullArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.type LIKE[cd] %@", @"standard"]]; 
+4
Jun 19 '10 at 17:23
source share



All Articles