![](/img/trans.png)
[英]Terminating app due to uncaught exception 'NSInternalInconsistencyException'
[英]TableView app terminated due to 'NSInternalInconsistencyException'
我正试图了解UITableViews以及随之而来的一切。 目前我有以下代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
-(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.textLabel setText:[NSString stringWithFormat:@"I am cell %d", indexPath.row]];
return cell;
}
- (IBAction)killItem {
NSIndexPath *indexToDelete = [NSIndexPath indexPathForRow:2 inSection:0];
[tbl deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexToDelete] withRowAnimation:UITableViewRowAnimationRight];
}
启动“killItem”函数时出现以下错误:
由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第0节中的行数无效。更新后的现有部分中包含的行数(10)必须等于该行中包含的行数更新前的部分(10),加上或减去从该部分插入或删除的行数(插入0,删除1)。
我理解它的方式tableViews基本上有一个委托和一个数据源,其中数据源确定tableView中应该有多少行。 通过stackoverflow的一些搜索,我发现当“数据源与现实不匹配”时,当它搜索不存在的行时,我已经删除了这个错误。
我可能已经弄错了,但这就是我的想法。 所以我的问题是,如何让这些匹配,以便我可以避免这个错误?
作为参考,我在不了解我需要做什么的情况下查看了以下帖子:
由于未捕获的异常'NSRangeException'终止应用程序,原因:'*** - [NSMutableArray objectAtIndex:]:索引1超出边界[0 .. 0]'
在killItem函数中添加[tbl reloadData]
, [tbl beginUpdate] ... [tbl endUpdate]
,似乎没有帮助我的问题eighter。
先谢谢你,Tobias Tovedal
Tobias,删除行时需要做的是
// tell the table view you're going to make an update
[tableView beginUpdates];
// update the data object that is supplying data for this table
// ( the object used by tableView:numberOfRowsInSection: )
[dataArray removeObjectAtIndex:indexPath.row];
// tell the table view to delete the row
[tableView deleteRowsAtIndexPaths:indexPath
withRowAnimation:UITableViewRowAnimationRight];
// tell the table view that you're done
[tableView endUpdates];
当您调用endUpdate
,从tableView:numberOfRowsInSection:
返回的数字tableView:numberOfRowsInSection:
必须与beginUpdate
的数字相同,减去已删除的行数。
这很容易,问题出在这里:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
apple使用的委托模式意味着您是负责通过其委托管理UITableView内容的人,这意味着,如果删除行,您还要负责从数据模型中删除数据。
因此,在删除行之后,将部分中的行数减少到“9”是有意义的,但是,您的函数总是返回10,从而抛出异常。
通常,在使用表时,内容会发生变化,NSMutableArray非常常见,你可以这样做:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayWithStuff count];
}
然后,从数组中删除对象( removeObjectAtIndex:
将自动更新行数。
(编辑:与Mike Hay大约同时回复,尝试遵循他的建议!我跳过了开始/结束更新,因为看起来你已经读过它了)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.