【发布时间】:2011-11-22 16:27:13
【问题描述】:
这几天我一直在努力解决这个问题。我需要在 beginUpdates/endUpdates 块内的 UITableView 中同时删除和插入一些行,但是一些插入的行的索引超过了原始表视图元素计数。我从Apple文档中获取有关批量插入和删除的示例代码并对其进行了修改以引起同样的问题,代码如下:
#import "MasterViewController.h"
@implementation MasterViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"Master", @"Master");
states = [[NSMutableArray arrayWithObjects:@"Arizona", @"California", @"New Jersey", @"Washington", nil] retain];
}
return self;
}
- (void)dealloc
{
[states release];
[super dealloc];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [states count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
cell.textLabel.text = [states objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[states removeObjectAtIndex:0];
[states removeObjectAtIndex:0];
[states removeObjectAtIndex:0];
[states insertObject:@"Alaska" atIndex:1];
[states insertObject:@"Georgia" atIndex:1];
[states insertObject:@"Wisconsin" atIndex:1];
NSArray *deleteIndexPaths = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:0 inSection:0],
[NSIndexPath indexPathForRow:1 inSection:0],
[NSIndexPath indexPathForRow:2 inSection:0],
nil];
NSArray *insertIndexPaths = [NSArray arrayWithObjects:
[NSIndexPath indexPathForRow:2 inSection:0],
[NSIndexPath indexPathForRow:3 inSection:0],
[NSIndexPath indexPathForRow:4 inSection:0],
nil];
UITableView *tv = (UITableView *)self.view;
[tv beginUpdates];
[tv insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationTop];
[tv deleteRowsAtIndexPaths:deleteIndexPaths withRowAnimation:UITableViewRowAnimationTop];
[tv endUpdates];
}
@end
当我运行它并点击任何行时,我得到以下异常:
*** Assertion failure in -[_UITableViewUpdateSupport _computeRowUpdates], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableViewSupport.m:386
Uncaught exception: Invalid table view update. The application has requested an update to the table view that is inconsistent with the state provided by the data source.
这段代码有什么我没有看到的根本错误吗?
【问题讨论】:
-
既然你本质上是在替换行,为什么不重新加载那些索引路径而不是删除和重新插入?...只是一个虽然
-
因为这是一个更简单的例子。在我的真实应用中,删除和插入的行数并不总是相同的。
标签: ios uitableview