How should I handle NSIndexSet from kvo to update table view?

I am starting to use the monitoring of key values, and the mutable array that I am observing gives me NSIndexSets (Ordered mutable to-many) in the change dictionary. The problem is presenting the table, as far as I know, wants me to give it NSArrays full of indexes.

I was thinking of implementing a custom method to translate one to the other, but it seems slow, and I get the impression that there should be a better way to do this by updating the table view when the array changes.

This is the method from my UITableViewDataSource.

 -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
     switch ([[change valueForKey:NSKeyValueChangeKindKey] unsignedIntValue]) {
         case NSKeyValueChangeSetting:
             NSLog(@"Setting Change");
             break;
         case NSKeyValueChangeInsertion:
             NSLog(@"Insertion Change");

             // How do I fit this:
             NSIndexSet * indexes = [change objectForKey:NSKeyValueChangeIndexesKey];

             // into this:
             [self.tableView insertRowsAtIndexPaths:<#(NSArray *)#> withRowAnimation:<#(UITableViewRowAnimation)#>

             // Or am I just doing it wrong?

             break;
         case NSKeyValueChangeRemoval:
             NSLog(@"Removal Change");
             break;
         case NSKeyValueChangeReplacement:
             NSLog(@"Replacement Change");
             break;
         default:
             break;
     }
 }
+3
source share
2 answers

. enumerateIndexesUsingBlock: NSIndexPath:

NSMutableArray * paths = [NSMutableArray array];
[indexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
        [paths addObject:[NSIndexPath indexPathWithIndex:index]];
    }];
[self.tableView insertRowsAtIndexPaths:paths
                      withRowAnimation:<#(UITableViewRowAnimation)#>];

, , :

NSUInteger sectionAndRow[2] = {sectionNumber, index};
[NSIndexPath indexPathWithIndexes:sectionAndRow
                           length:2];
+11

NSIndexSet:

@interface NSIndexSet (mxcl)
- (NSArray *)indexPaths;
@end

@implementation NSIndexSet (mxcl)

- (NSArray *)indexPaths {
    NSUInteger rows[self.count];
    [self getIndexes:rows maxCount:self.count inIndexRange:NULL];
    NSIndexPath *paths[self.count];
    for (int x = 0; x < self.count; ++x)
        paths[x] = [NSIndexPath indexPathForRow:rows[x] inSection:0];
    return [NSArray arrayWithObjects:paths count:self.count];
}

@end

NSMutableArray, - , .

+1

All Articles