我开始使用键值观察,并且我正在观察的可变数组在更改字典中为我提供了 NSIndexSets (有序可变对多)。据我所知,问题是表视图希望我给它充满索引的 NSArrays。
我考虑过实现一种自定义方法来将一个方法转换为另一个方法,但这似乎很慢,而且我的印象是必须有更好的方法来使该表视图在数组更改时更新。
这是我的 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: http://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSIndexSet_Class/Reference/Reference.html#//apple_ref/doc/uid/20002197-SW17并将每个索引粘贴到NSIndexPath
object:
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];
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)