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

前端 未结 11 1586
-上瘾入骨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 10:50

    The best answer is to this is Apple's own documentation.

    enter image description here

    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. However, in many cases, you need to do things that only an NSArray can do, so you sacrifice the speed for those abilities.

    NSSet

    • Primarily access items by comparison
    • Unordered
    • Does not allow duplicates

    NSArray

    • Can access items by index
    • Ordered
    • Allows duplicates

    That's all there really is to it! Let me know if that helps.

提交回复
热议问题