从UITableView删除单元格 - 错误

时间:2011-07-14 14:42:48

标签: iphone ios ipad uitableview

在我的iPhone应用程序中,我有一个带有以下方法的UITableView

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [tableArrays count];
}

请注意tableArrays是一个类变量(NSMutableArrays的NSMutableArray - 表示我的tableView中每个部分的一个NSMutableArray)。现在,UITableView支持编辑,我有以下方法

- (void)tableView:(UITableView *)theTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    ...some code...

    NSLog(@"tableArrays count is %i",[tableArrays count]);
    [tableArrays removeObjectAtIndex:indexPath.section];
    NSLog(@"tableArrays is now %@",tableArrays);
    NSLog(@"tableArrays count is now %i",[tableArrays count]);


   [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

}

所以,我运行应用程序,我的表视图中有两个部分。行删除工作正常,除非我删除节中的最后一行。当我删除第1部分的最后一行时,根据上面的代码,我看到以下输出:

tableArrays count is 2
tableArrays is now (("Blah1","Blah2"))
tableArrays count is now 1

很明显,我的tableArrays计数减少了一个,但我收到以下错误:

...The number of sections contained in the tableView after the update (1) must be qual to the number of sections contained in the table view before the update (2), plus or minus the number of sections inserted or dleted (0 inserted, 0 deleted).'

2 个答案:

答案 0 :(得分:1)

我想在-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;中您将返回对象的总数,并且您只想显示一个部分。

尝试在此方法中返回一个。

您还应该在[tableArrays count]中返回-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;

它应该像这样工作得更好。

中的section也是如此

[tableArrays removeObjectAtIndex:section];?您的意思是indexPath.section吗?

感谢评论,所以返回分区数的方法是正确的,但你要这样做以删除一个单元格。

NSLog(@"tableArrays count is %i",[tableArrays count]);
NSMutableArray *sectionArray = [tableArrays objectAtIndex:indexPath.section];
[sectionArray removeObjectAtIndex:indexPath.row];
//[tableArrays removeObjectAtIndex:indexPath.section];
NSLog(@"tableArrays is now %@",tableArrays);
NSLog(@"tableArrays count is now %i",[tableArrays count]);

答案 1 :(得分:1)

关键是使用

[tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];

当您尝试删除部分中的最后一行时。

相关问题