删除数组中的最后一项和UITableView

时间:2014-05-14 13:35:31

标签: ios objective-c uitableview nsmutablearray

我有一个tableView,其中包含一个值的数组。以下是numberOfRowsInSection的样子

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [allPasses count];
}

删除行时,此代码会运行

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [allPasses removeObjectAtIndex:indexPath.row];
        // Delete the row from the data source
        PassWhizEntity *passToRemove = self.allPasses[indexPath.row];
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        // Get the local context
        NSManagedObjectContext *localContext    = [NSManagedObjectContext MR_contextForCurrentThread];
        [passToRemove MR_deleteInContext:localContext];
        [localContext MR_save];


    }

这很好用,您可以删除任何行,但是当您删除最后一行时,应用程序崩溃并且您收到此错误。

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

但我不知道如何解决这个问题。我确信这是一个非常简单的修复,但我尝试在数组中添加一个,我不知道还能做什么。任何想法将不胜感激!

1 个答案:

答案 0 :(得分:2)

它无法正常工作,因为这些行的顺序错误:

[allPasses removeObjectAtIndex:indexPath.row];
// Delete the row from the data source
PassWhizEntity *passToRemove = self.allPasses[indexPath.row];

目前你所拥有的只是一个隐藏的问题,直到你到达最后一个项目。

反转这些行的顺序,以便在从数组中删除项目之前将其删除。

相关问题