Stop Tableview from crashing when the array is empty?

At first my table view is empty, and then you can add your own cells to it. When you delete those cells, everything works fine. However, if you delete the last cell, then my NSMutableArray has no objects in it, and I get this error in my console (also, I’m using Core Data to save the cells):

*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[_PFBatchFaultingArray objectAtIndex:]: index (123150308) beyond bounds (1)'

I also tried putting in this line of code, but I still get the same results:

//arr is my mutable array
        if ([arr count] == 0) {
        NSLog(@"No Cells");
    }

This is how I delete an object from the table view:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [arr removeObjectAtIndex:0];
        [context deleteObject:[arr objectAtIndex:0]];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

How would I solve this problem?

Ok.

There are two problems I have found in you code.

1- Why you are removing every time object at Index 0 ?

2- After removing an object from array [arr removeObjectAtIndex:0];
than from the same array of index you are passing an object to core Data to delete it

[context deleteObject:[arr objectAtIndex:0]];

This might be the problem.

This will surely help you.

Use this:

[context deleteObject:[arr objectAtIndex:indexPath.row]];

[arr removeObjectAtIndex:indexPath.row];

Thanks :)

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Stop Tableview from crashing when the array is empty?

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录