[IOS] NSIndexPath , NSIndexSet , NSRange 之间的区别比较

长平狐 发布于 2012/10/25 13:08
阅读 1K+
收藏 0

The NSIndexSet class represents an immutable collection of unique unsigned integers, known as indexes because of the way they are used. This collection is referred to as a index set.

You use index sets in your code to store indexes into some other data structure. For example, given an NSArray object, you could use an index set to identify a subset of objects in that array.

Each index value can appear only once in the index set. This is an important concept to understand and is why you would not use index sets to store an arbitrary collection of integer values. To illustrate how this works, if you created an NSIndexSet object with the values 4, 5, 2, and 5, the resulting set would only have the values 4, 5, and 2 in it. Because index values are always maintained in sorted order, the actual order of the values when you created the set would be 2, 4, and then 5.

In most cases, using an index set is more efficient than storing a collection of individual integers. Internally, the NSIndexSet class represents indexes using ranges. For maximum performance and efficiency, overlapping ranges in an index set are automatically coalesced—that is, ranges merge rather than overlap. Thus, the more contiguous the indexes in the set, the fewer ranges are required to specify those indexes.

The designated initializers of the NSIndexSet class are: initWithIndexesInRange: and initWithIndexSet:.

You must not subclass the NSIndexSet class.

The mutable subclass of NSIndexSet is NSMutableIndexSet.


The NSIndexPath class represents the path to a specific node in a tree of nested array collections. This path is known as an index path.

Each index in an index path represents the index into an array of children from one node in the tree to another, deeper, node. For example, the index path specifies the path shown in Figure 1.

A structure used to describe a portion of a series—such as characters in a string or objects in an NSArray object.

typedef struct _NSRange {
      NSUInteger location;
      NSUInteger length;
} NSRange;
The start index (0 is the first, as in C arrays).
The number of items in the range (can be 0).

NSIndexSet 用来让你从某个 data structure 里面提取一部分东西出来成为一个新的东西。
比如你有一个 NSArray, 里面是
(one, two, three, four, five)
然后你造了个 indexSet 的内容是 1,2,3,5
然后你把它套到那个 array 上,就是 (one, two,three,five)

NSIndexPath 让你精确指定一个树结构 data structure 里面的某个节点的数据
比如你有一个 NSArray, 里面很多节点,每个节点又是一个 NSArray,每个节点的这个里面又是一个NSArray,然后下面又是一个  NSArray
这样简单说起来,你有一个四层的 NSarray ,每层下面都有好多个 NSArray。
然后你造一个  NSIndexPath
你就可以拿它访问      第一层第三个节点之下第四个节点第二个节点的数据

NSRange 就是 从 x 到 y
比如 3 到 6

比如你有一个 NSString, 内容是 "go home and eat"
你就可以拿这个range截取这个 NSString, 3-6 就是 “home”


NSIndexPath 盗梦空间的感觉