UITableView删除行在iOS中崩溃



我正在尝试从iOS的UITableView中删除行。

UITableView中,我显示了位于文档目录中的文件列表。

我想从文档目录中删除文件。

这是删除的代码。

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
        UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        self.fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        [self.fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.txt",cell.textLabel.text]] error:NULL];

        [tableView reloadData];
    }
}

错误信息是

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

但是当我试图删除时,它崩溃了。

请帮帮我。

您的方法numberOfRowsInSection没有得到正确更新。您需要确保无论何时添加或删除项,它返回的值都会发生变化。

通常最好将您正在处理的所有数据输入NSMutableArray,然后在numberOfRowsInSection中,您将使用类似return [arrayOfData count];的东西。

它应该反映回返回行数的方法。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return array count
}

删除数组中的元素。步骤:
1:从数组
中搜索元素索引2:用户removeObjectAtIndex方法删除

最新更新