Fast enumeration on an NSIndexSet

后端 未结 6 726
南旧
南旧 2020-12-14 14:13

Can you fast enumerate a NSIndexSet? if not, what\'s the best way to enumerate the items in the set?

相关标签:
6条回答
  • 2020-12-14 14:38

    Fast enumeration must yield objects; since an NSIndexSet contains scalar numbers (NSUIntegers), not objects, no, you cannot fast-enumerate an index set.

    Hypothetically, it could box them up into NSNumbers, but then it wouldn't be very fast.

    0 讨论(0)
  • 2020-12-14 14:38

    Supposing you have an NSTableView instance (let's call it *tableView), you can delete multiple selected rows from the datasource (uhm.. *myMutableArrayDataSource), using:

    [myMutableArrayDataSource removeObjectsAtIndexes:[tableView selectedRowIndexes]];
    

    [tableView selectedRowIndexes] returns an NSIndexSet. No need to start enumerating over the indexes in the NSIndexSet yourself.

    0 讨论(0)
  • 2020-12-14 14:39

    Short answer: no. NSIndexSet does not conform to the <NSFastEnumeration> protocol.

    0 讨论(0)
  • 2020-12-14 14:45

    A while loop should do the trick. It increments the index after you use the previous index.

    /*int (as commented, unreliable across different platforms)*/
    NSUInteger currentIndex = [someIndexSet firstIndex];
    while (currentIndex != NSNotFound)
    {
        //use the currentIndex
    
        //increment
        currentIndex = [someIndexSet indexGreaterThanIndex: currentIndex];
    }
    
    0 讨论(0)
  • 2020-12-14 14:50

    These answers are no longer true for IndexSet in Swift 5. You can perfectly get something like:

    let selectedRows:IndexSet = table.selectedRowIndexes
    

    and then enumerate the indices like this:

    for index in selectedRows {
       // your code here.
    }
    
    0 讨论(0)
  • 2020-12-14 14:51

    In OS X 10.6+ and iOS SDK 4.0+, you can use the -enumerateIndexesUsingBlock: message:

    NSIndexSet *idxSet = ...
    
    [idxSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
      //... do something with idx
      // *stop = YES; to stop iteration early
    }];
    
    0 讨论(0)
提交回复
热议问题