Tob*_*dal 7 iphone objective-c uitableview ios
我正试图了解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];
}
Run Code Online (Sandbox Code Playgroud)
启动"killItem"函数时出现以下错误:
由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因:'无效更新:第0节中的行数无效.更新后的现有部分中包含的行数(10)必须等于该行中包含的行数更新前的部分(10),加上或减去从该部分插入或删除的行数(插入0,删除1).
我理解它的方式tableViews基本上有一个委托和一个数据源,其中数据源确定tableView中应该有多少行.通过stackoverflow的一些搜索,我发现当"数据源与现实不匹配"时,当它搜索不存在的行时,我已经删除了这个错误.
我可能已经弄错了,但这就是我的想法.所以我的问题是,如何让这些匹配,以便我可以避免这个错误?
作为参考,我在不了解我需要做什么的情况下查看了以下帖子:
由于未捕获的异常'NSRangeException'终止应用程序,原因:'*** - [NSMutableArray objectAtIndex:]:索引1超出边界[0 .. 0]'
添加[tbl reloadData],[tbl beginUpdate] ... [tbl endUpdate]在killItem函数中,似乎没有帮助我的问题eighter.
先谢谢你,Tobias Tovedal
Mik*_*Hay 13
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];
Run Code Online (Sandbox Code Playgroud)
当您调用endUpdate返回的数字tableView:numberOfRowsInSection:必须与beginUpdate减去的行数相同时删除的行数.
Can*_*Can 12
这很容易,问题出在这里:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 10;
}
Run Code Online (Sandbox Code Playgroud)
apple使用的委托模式意味着您是负责通过其委托管理UITableView内容的人,这意味着,如果删除行,您还要负责从数据模型中删除数据.
因此,在删除一行之后,将部分中的行数减少到"9"是有意义的,但是,您的函数总是返回10,从而抛出异常.
通常,在使用表时,内容会发生变化,NSMutableArray非常常见,你可以这样做:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayWithStuff count];
}
Run Code Online (Sandbox Code Playgroud)
然后,removeObjectAtIndex:从数组中删除object()将自动更新行数.
(编辑:与Mike Hay大约同时回复,尝试遵循他的建议!我跳过了开始/结束更新,因为看起来你已经读过它了)
| 归档时间: |
|
| 查看次数: |
14702 次 |
| 最近记录: |