Question

I have a tableView with one section in it which contains an array of values. Here is what the numberOfRowsInSection looks like

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

When you delete a row this code runs

- (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];


    }

This works great and you can delete any rows but when you delete the last row the app crashes and you get this error.

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

But I don't know how to fix this. I am sure its quite a simple fix but I have tried adding one to the array and I'm not sure what else to do. Any ideas would be appreciated!

Was it helpful?

Solution

It doesn't work properly because these lines are in the wrong order:

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

all you have at the moment is a hidden issue until you get to the last item.

Reverse the order of those lines so that you get the item to delete before you remove it from the array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top