When do I use NSSet and when do I use NSArray? (using Xcode 8.2.1 / iOS 10)

When do I use NSSet and when do I use NSArray? (using Xcode 8.2.1 / iOS 10)

Question: When do I use NSSet and when do I use NSArray?

Answer: It depends.
If (you have duplicate entries, care about the order or want to access an element by an index) THEN use NSArray
ELSE use NSSet

Basically if the order is not important to you NSSet will be faster for you as far as searching items.

If you look at our previous blog entry you will see we were talking about NSArrays and NSSets.

Let’s look at how NSLog prints out the NSSet items in each collection – shall we?

//Code
NSSet *mySet = [NSSet setWithArray:@[@"Hit",@"me",@"with",@"your",@"best",@"shot"]];
 NSLog(@"My set initially looks like this: %@",mySet);

//Output
My set initially looks like this: {(
 shot,
 me,
 your,
 Hit,
 with,
 best
)}

It’s not the same – is it? That’s because with NSSet the items are accessed by comparison where order does not matter
With the NSArray order matters. Take a minute and study the output from the NSSet – see the pattern of how it printed?

Therefore making NSSets and UNORDERED Collections and NSArrays ORDERED Collections

So, you can decide what’s best for you with the knowledge that NSSets are faster.

Now, if we revisit the blog on FAST ENUMERATION we can now understand that we can search backwards for an NSArray with the following code but not with NSSet

//Code
for (NSString *myStr in [myArray reverseObjectEnumerator])
{
NSLog(@"Value =%@",myStr);
}

//Output
Value =shot
Value =best
Value =your
Value =with
Value =me
Value =Hit

Very cool……that’s all I can say 🙂

-Angelo Koutsogiannis

Leave a Reply

Your email address will not be published. Required fields are marked *