我应该如何处理来自kvo的NSIndexSet更新表视图? [英] How should I handle the NSIndexSet from kvo to update a table view?
问题描述
我开始使用键值观察,并且我观察的可变数组给我在更改字典中的NSIndexSets(有序可变对多)。问题是表视图,据我所知我希望我给它NSArrays充分的索引。
I am starting out using key value observing, and the mutable array I'm observing gives me NSIndexSets (Ordered mutable to-many) in the change dictionary. The problem is the table view as far as I know wants me to give it NSArrays full of indexes.
我想到实现一个自定义方法来转换一个到另一个,但是这看起来很慢,我得到的印象是,必须有一个更好的方法来使数据表更改时更新此表视图。
I thought about implementing a custom method to translate one to the other, but this seems slow and I get the impression there must be a better way to make this table view update when the array changes.
这是从UITableViewDataSource的方法。 / p>
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;
}
}
推荐答案
看起来很容易。使用 enumerateIndexesUsingBlock:
,并将每个索引粘贴到 NSIndexPath
对象:
This seems easy enough. Enumerate the index set using enumerateIndexesUsingBlock:
and stick each index into an NSIndexPath
object:
NSMutableArray * paths = [NSMutableArray array];
[indexes enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
[paths addObject:[NSIndexPath indexPathWithIndex:index]];
}];
[self.tableView insertRowsAtIndexPaths:paths
withRowAnimation:<#(UITableViewRowAnimation)#>];
如果你的表视图有部分,这只是一个更复杂,因为你需要正确的节号,并在索引路径中指定它:
If your table view has sections, it's only a bit more complicated, because you'll need to get the correct section number, and specify it in the index path:
NSUInteger sectionAndRow[2] = {sectionNumber, index};
[NSIndexPath indexPathWithIndexes:sectionAndRow
length:2];
这篇关于我应该如何处理来自kvo的NSIndexSet更新表视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!