0

我正在尝试从UITableViewiOS 中删除行。

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).'

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

请帮我。

4

2 回答 2

3

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

通常最好将您正在使用的所有数据输入一个NSMutableArray然后输入numberOfRowsInSection,您将使用类似return [arrayOfData count];.

于 2013-06-19T14:57:59.070 回答
1

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

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

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

于 2013-06-19T15:06:16.000 回答