Tag Archives: NSSet

How to test if an NSArray or NSSet contains an object

There’s a handy method in the NSArray class that lets us check if an array contains a particular object or not. The containsObject method returns a BOOL for us to evaluate.

Consider this:

Likewise, we can check if our array does not contain a particular object by testing the opposite:

Both the NSMutableArray and NSSet classes has the same method, so we can check for the (un-)presence of our objects in mutable arrays and sets the same way.

What is the difference between NSSet, NSArray and NSDictionary

Bottle CollectionAll three are collection objects that can hold any number of other Objective C objects. I’m sure you’re familiar with the NSArray class, but the other two may sound a bit exotic. Let me explain them all here.

To do this I’m using NSString objects, but all three can pretty much hold any NSObject you encounter – you can even mix object types. For example, you can mix NSString and NSDate objects in the same collection.


An NSArray can hold objects in a sorted order. So object1 is always object1, and object2 is always object2. You can retrieve the first and last object from the array.

Here’s how to create one:

This will print all elements in order:

2014-04-07 19:58:14.541 SetTest[542:303] One
2014-04-07 19:58:14.543 SetTest[542:303] Two
2014-04-07 19:58:14.543 SetTest[542:303] Three
2014-04-07 19:58:14.544 SetTest[542:303] Four
2014-04-07 19:58:14.544 SetTest[542:303] Five
2014-04-07 19:58:14.544 SetTest[542:303] Six


An NSSet is much like an NSArray, the only difference is that the objects it holds are not ordered. So when you retrieve them they may come back in any random order, based on how easy it is for the system to retrieve them.

You would typically use a set when access speed is of the essence and order doesn’t matter, or is determined by other means (through a predicate or sort descriptor). Core Data for example uses sets when managed objects are accessed via a to-many relationship.

You can turn NSSets into NSArrays and back, and you can fast-enumerate an NSSet too:

This may print something like this:

2014-04-07 19:42:59.123 SetTest[477:303] Five
2014-04-07 19:42:59.123 SetTest[477:303] Six
2014-04-07 19:42:59.124 SetTest[477:303] One
2014-04-07 19:42:59.124 SetTest[477:303] Three
2014-04-07 19:42:59.124 SetTest[477:303] Four
2014-04-07 19:42:59.125 SetTest[477:303] Two


The NSDictionary class is a bit of a magical one: it stores objects as key value pairs. Objects are not ordered, but can be retrieved simply by addressing them with an arbitrary string value.

Here we create one with three keys and values, then loop through it:

This will print:

2014-04-07 20:12:52.100 SetTest[580:303] name: Chuck Norris
2014-04-07 20:12:52.102 SetTest[580:303] title: Movie Star
2014-04-07 20:12:52.103 SetTest[580:303] tvShow: Walker, Texas Ranger