NSIndexSet “-indexAtIndex:”?

后端 未结 4 1645
执念已碎
执念已碎 2020-12-18 20:57

This feels like a dumb question because it seems to me like my use case must be quite common.

Say I want to represent a sparse set of indexes with an NSIndexSet (whi

4条回答
  •  借酒劲吻你
    2020-12-18 21:39

    NSIndexSet isn't designed for that sort of access. Usually, you enumerate through the indexes in a set like so:

    NSUInteger idx = [theSet indexGreaterThanOrEqualToIndex: 0];
    while (idx != NSNotFound) {
        // idx equals the next index in the set.
        idx = [theSet indexGreaterThanIndex: idx];
    }
    

    @Richard points out this for loop is simpler:

    for (NSUInteger i = [indexSet firstIndex]; i != NSNotFound; i = [indexSet indexGreaterThanIndex:i]) {
        // i equals the next index in the set.
    }
    

    There's some block-based methods that are new to NSIndexSet as of Mac OS X 10.6/iOS 4.0, but I haven't reviewed them as of yet.

    It should be trivial to modify the above example to keep a running count of indexes and stop when it reaches the fourth index in the set. ;)

提交回复
热议问题