我开始使用键值观察,而我正在观察的可变数组在更改字典中为我提供了 NSIndexSets (Ordered mutable to-many)。据我所知,问题是 TableView 希望我给它提供充满索引的 NSArrays。
我考虑过实现一个自定义方法来将一个方法转换为另一个方法,但这看起来很慢,而且我觉得必须有更好的方法在数组更改时更新此 TableView 。
这是来 self 的 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;
}
}
最佳答案
这看起来很简单。使用 enumerateIndexesUsingBlock:
枚举索引集并将每个索引粘贴到 NSIndexPath
对象中:
NSMutableArray * paths = [NSMutableArray array];
[indexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
[paths addObject:[NSIndexPath indexPathWithIndex:index]];
}];
[self.tableView insertRowsAtIndexPaths:paths
withRowAnimation:<#(UITableViewRowAnimation)#>];
如果你的 TableView 有部分,它只会更复杂一点,因为你需要获得正确的部分号,并在索引路径中指定它:
NSUInteger sectionAndRow[2] = {sectionNumber, index};
[NSIndexPath indexPathWithIndexes:sectionAndRow
length:2];
关于objective-c - 我应该如何处理来自 kvo 的 NSIndexSet 来更新 TableView ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6237311/