Getting an object from an NSSet Getting an object from an NSSet objective-c objective-c

Getting an object from an NSSet


There are several use cases for a set. You could enumerate through (e.g. with enumerateObjectsUsingBlock or NSFastEnumeration), call containsObject to test for membership, use anyObject to get a member (not random), or convert it to an array (in no particular order) with allObjects.

A set is appropriate when you don't want duplicates, don't care about order, and want fast membership testing.


NSSet doesn't have a method objectAtIndex:

Try calling allObjects which returns an NSArray of all the objects.


it is possible to use filteredSetUsingPredicate if you have some kind of unique identifier to select the object you need.

First create the predicate (assuming your unique id in the object is called "identifier" and it is an NSString):

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"identifier == %@", identifier];

And then choose the object using the predicate:

NSObject *myChosenObject = [mySet filteredSetUsingPredicate:myPredicate].anyObject;