When is it better to use an NSSet over an NSArray?

前端 未结 11 1555
-上瘾入骨i
-上瘾入骨i 2020-12-12 10:27

I have used NSSets many times in my apps, but I have never created one myself.

When is it better to use an NSSet as opposed to an NSArray and why?

相关标签:
11条回答
  • 2020-12-12 11:00

    When the order of the items in the collection is not important, sets offer better performance for finding items in the collection.

    The reason is that a set uses hash values to find items (like a dictionary) while an array has to iterate over its entire contents to find a particular object.

    0 讨论(0)
  • 2020-12-12 11:01

    NSOrderedSet is available in iOS 5+ so with that the main difference becomes whether you want duplicate objects in the data structure.

    0 讨论(0)
  • 2020-12-12 11:03

    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

    0 讨论(0)
  • 2020-12-12 11:08

    The main differences have already been given in other answers.

    I'd just like to note that because of the way sets and dictionaries are implemented (i.e. using hashes),one should be careful not to use mutable objects for the keys.

    If a key is mutated then the hash will (probably) change too, pointing to a different index/bucket in the hash table. The original value won't be deleted and will actually be taken into account when enumerating or asking the structure for its size/count.

    This can lead to some really hard to locate bugs.

    0 讨论(0)
  • 2020-12-12 11:10

    Just to add a bit of it i use set sometimes just to remove duplicates from array like :-

    NSMutableSet *set=[[NSMutableSet alloc]initWithArray:duplicateValueArray]; // will remove all the duplicate values
    
    0 讨论(0)
提交回复
热议问题