NSIndexSet 用法
NSMutableIndexSet *idxSet = [[NSMutableIndexSet alloc] init];
[idxSet addIndex:5];
[idxSet addIndex:2];
[idxSet addIndex:8];
[idxSet addIndex:12];
// 添加 4到13的索引值
[idxSet addIndexesInRange:NSMakeRange(4, 10)];
[idxSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop)
{
NSLog(@"%lu", (unsigned long)idx);
}];
打印结果:
2013-11-29 11:34:52.328 Tabels[862:a0b] 2
2013-11-29 11:34:52.328 Tables[862:a0b] 4
2013-11-29 11:34:52.328 Tables[862:a0b] 5
2013-11-29 11:34:52.329 Tables[862:a0b] 6
2013-11-29 11:34:52.329 Tables[862:a0b] 7
2013-11-29 11:34:52.330 Tables[862:a0b] 8
2013-11-29 11:34:52.330 Tables[862:a0b] 9
2013-11-29 11:34:52.330 Tables[862:a0b] 10
2013-11-29 11:34:52.331 Tables[862:a0b] 11
2013-11-29 11:34:52.331 Tables[862:a0b] 12
2013-11-29 11:34:52.332 Tables[862:a0b] 13
NSIndexSet同时还包含许多方法判断是否包含某区间或者从一个索引值内获取临近的区间内的索引。如下代码:
NSUInteger a = [idxSet indexGreaterThanIndex:5];
NSUInteger b = [idxSet indexLessThanIndex:5];
NSUInteger c = [idxSet indexGreaterThanOrEqualToIndex:5];
NSUInteger d = [idxSet indexLessThanOrEqualToIndex:5];
NSLog(@"a = %lu, b = %lu, c = %lu, d = %lu", (unsigned long)a,(unsigned long)b,(unsigned long)c,(unsigned long)d);
结果:2013-11-29 15:42:23.053 Tables[1165:a0b] a = 6, b = 4, c = 5, d = 5
NSIndexSet还取一个NSRange范围中的交集,然后还可以以相反的顺序进行枚举。
这个需求需要使用NSIndexSet的enumerateIndexesInRange:options:usingBlock:方法,如下代码
[idxSet enumerateIndexesInRange:NSMakeRange(4, 4) options:NSEnumerationReverse usingBlock:^(NSUInteger idx, BOOL*stop) {
NSLog(@"%lu", (unsigned long)idx);
}]
结果是:
2013-11-29 15:49:38.413 Tables[1187:a0b] 7
2013-11-29 15:49:38.414 Tables[1187:a0b] 6
2013-11-29 15:49:38.414 Tables[1187:a0b] 5
2013-11-29 15:49:38.415 Tables[1187:a0b] 4
由于idxSet的本身的区间是2,4 -13,NSMakeRange(4, 4) 的区间是4 - 7,取交集就是4-7,然后反序就是7,6,5,4.
通过NSIndexSet获取数组
NSMutableIndexSet *idxSet1 = [[NSMutableIndexSet alloc] init];
[idxSet1 addIndex:1];
[idxSet1 addIndexesInRange:NSMakeRange(3, 3)];
[idxSet1 addIndexesInRange:NSMakeRange(7, 2)];
NSArray *array = @[@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9"];
NSArray *result = [array objectsAtIndexes:idxSet1];
[result enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL*stop) {
NSLog(@"%@",obj);
}];
结果是:
2013-11-29 15:59:03.961 Tables[1209:a0b] 1
2013-11-29 15:59:03.961 Tables[1209:a0b] 3
2013-11-29 15:59:03.961 Tables[1209:a0b] 4
2013-11-29 15:59:03.962 Tables[1209:a0b] 5
2013-11-29 15:59:03.962 Tables[1209:a0b] 7
2013-11-29 15:59:03.963 Tables[1209:a0b] 8