7

I'm a bit new to Cocoa and I was reading about NSIndexSet. Why is it necessary? It seems to me that NSIndexSet is nothing but a NSSet of integers, is that right? What's the purpose of creating a separate collection alltogether?

S.L. Barth
  • 7,954
  • 71
  • 47
  • 62
Tony
  • 30,345
  • 9
  • 45
  • 77

1 Answers1

12

There are a couple reasons:

  1. NSIndexSet stores unsigned integer primitive types, whereas NSSet stores objects.
  2. NSIndexSet is optimized for storing unsigned integers, specifically a set of integers into another data structure like an NSArray.
mipadi
  • 359,228
  • 81
  • 502
  • 469
  • 1
    To elaborate on #2, NSIndexSet lets you iterate through the indexes in order or in reverse order. An NSSet is unordered, and an NSOrderedSet is manually ordered (meaning you can break the order by inserting an object at the wrong position). – Peter Hosey Dec 19 '11 at 04:29
  • Got it. Another thing I just noticed. NSIndexSet actually uses NSRange to store consecutive indexes, indeed very optimized for storing index value into other collections. – Tony Dec 19 '11 at 07:37
  • Operations over `NSSet` are O(1) (hashing), while most of the `NSIndexSet` operations are O(N) (looping). – alex-i Aug 22 '16 at 07:57