Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 819
dontWatchMyProfile Avatar asked Jun 19 '10 17:06

dontWatchMyProfile


People also ask

What's a difference between NSArray and NSSet?

The main difference is that NSArray is for an ordered collection and NSSet is for an unordered collection. There are several articles out there that talk about the difference in speed between the two, like this one. If you're iterating through an unordered collection, NSSet is great.

What is NSArray Objective C?

An object representing a static ordered collection, for use instead of an Array constant in cases that require reference semantics.


1 Answers

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == %@", @"standard"]; NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate]; id firstFoundObject = nil; firstFoundObject =  filteredArray.count > 0 ? filteredArray.firstObject : nil; 

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.

like image 176
Ole Begemann Avatar answered Oct 14 '22 14:10

Ole Begemann