- #import <Foundation/Foundation.h>
- int main(int argc, const charchar * argv[]) {
- @autoreleasepool {
- /* 索引集合,可以用于数组多元素的提取 */
- NSIndexSet *indexSet1 = [[NSIndexSet alloc] initWithIndex: 1];
- NSIndexSet *indexSet2 = [[NSIndexSet alloc] initWithIndexSet: indexSet1];
- NSIndexSet *indexSet3 = [[NSIndexSet alloc] 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 = [arr1 objectsAtIndexes: indexSet3];
- NSLog(@"arr1:%@", arr1);
- NSLog(@"arr2:%@", arr2);
- /* 提取离散下标数组.需要注意的是,index集合是从小到大排序 */
- NSMutableIndexSet *mSet3 = [[NSMutableIndexSet alloc] init];
- [mSet3 addIndex: 2];
- [mSet3 addIndex: 0]; /* 即使先加入2后加入0,也是从小到大按序排列,从数组打印可以看出 */
- NSLog(@"mSet3:%@", mSet3);
- NSArray *arr3 = [arr1 objectsAtIndexes: mSet3];
- NSLog(@"arr3:%@", arr3);
- }
- return 0;
- }
输出结果:
- 2015-11-25 22:21:51.495 TestNSIndexSet[493:14234] indexSet1:<NSIndexSet: 0x1002068b0>[number of indexes: 1 (in 1 ranges), indexes: (1)]
- 2015-11-25 22:21:51.496 TestNSIndexSet[493:14234] indexSet2:<NSIndexSet: 0x100206910>[number of indexes: 1 (in 1 ranges), indexes: (1)]
- 2015-11-25 22:21:51.496 TestNSIndexSet[493:14234] indexSet3:<NSIndexSet: 0x1002069b0>[number of indexes: 3 (in 1 ranges), indexes: (2-4)]
- 2015-11-25 22:21:51.497 TestNSIndexSet[493:14234] arr1:(
- One,
- "Two thing",
- three,
- "four test",
- Five,
- six
- )
- 2015-11-25 22:21:51.497 TestNSIndexSet[493:14234] arr2:(
- three,
- "four test",
- Five
- )
- 2015-11-25 22:21:51.497 TestNSIndexSet[493:14234] mSet3:<NSMutableIndexSet: 0x100208410>[number of indexes: 2 (in 2 ranges), indexes: (0 2)]
- 2015-11-25 22:21:51.497 TestNSIndexSet[493:14234] arr3:(
- One,
- three
- )