NSIndexset
NSIndexSet同时还包含许多方法判断是否包含某区间或者从一个索引值内获取临近的区间内的索引。如下代码:
"NSUIntegera = [idxSet indexGreaterThanIndex:5];
NSUIntegerb = [idxSet indexLessThanIndex:5];
NSUIntegerc = [idxSet indexGreaterThanOrEqualToIndex:5];
NSUIntegerd = [idxSet indexLessThanOrEqualToIndex:5];
NSLog(@"a = %lu, b = %lu, c = %lu, d = %lu", (unsignedlong)a,(unsignedlong)b,(unsignedlong)c,(unsignedlong)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:方法,如下代码
[idxSetenumerateIndexesInRange:NSMakeRange(4,4)options:NSEnumerationReverse usingBlock:^(NSUIntegeridx, BOOL*stop) {
NSLog(@"%lu", (unsignedlong)idx);
}]
NSIdexset可用于取出数组中的多个值
NSIndexSet*indexSet1= [[NSIndexSetalloc]initWithIndex:1];
NSIndexSet*indexSet2= [[NSIndexSetalloc]initWithIndexSet:indexSet1];
NSIndexSet*indexSet3= [[NSIndexSetalloc]initWithIndexesInRange: NSMakeRange(2,3)];
NSLog(@"indexSet1:%@", indexSet1);
NSLog(@"indexSet2:%@", indexSet2);
NSLog(@"indexSet3:%@", indexSet3);
/* 快速初始化数组 */
NSArray*arr1= @[@"One",@"Two thing",@"three",@"four test",@"Five",@"six"];
/* 提取连续下标子数组 */
NSArray*arr2= [arr1objectsAtIndexes:indexSet3];
NSLog(@"arr1:%@", arr1);
NSLog(@"arr2:%@", arr2);
/* 提取离散下标数组.需要注意的是,index集合是从小到大排序 */
NSMutableIndexSet*mSet3= [[NSMutableIndexSetalloc]init];
[mSet3addIndex:2];
[mSet3addIndex:0];/* 即使先加入2后加入0,也是从小到大按序排列,从数组打印可以看出 */
NSLog(@"mSet3:%@", mSet3);
NSArray*arr3= [arr1objectsAtIndexes:mSet3];
NSLog(@"arr3:%@", arr3);
以下是打印结果
2015-11-2522:21:51.495TestNSIndexSet[493:14234]indexSet1:[number ofindexes:1(in1ranges),indexes: (1)]
2015-11-2522:21:51.496TestNSIndexSet[493:14234]indexSet2:[number ofindexes:1(in1ranges),indexes: (1)]
2015-11-2522:21:51.496TestNSIndexSet[493:14234]indexSet3:[number ofindexes:3(in1ranges),indexes: (2-4)]
2015-11-2522:21:51.497TestNSIndexSet[493:14234]arr1:(
One,
"Two thing",
three,
"four test",
Five,
six
)
2015-11-2522:21:51.497TestNSIndexSet[493:14234]arr2:(
three,
"four test",
Five
)
2015-11-2522:21:51.497TestNSIndexSet[493:14234]mSet3:[number ofindexes:2(in2ranges),indexes: (02)]
2015-11-2522:21:51.497TestNSIndexSet[493:14234]arr3:(
One,
three
)