UITableView reloadData within catch block

2019-08-18 01:28发布

I'm trying to add a catch block within the UITableView but it doesn't do anything.

[self.dataArray addObject:@"xyz"];
@try {
    [self.tableView beginUpdates];
    //try with nil to go to catch block
    [self.tableView insertRowsAtIndexPaths:nil withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView endUpdates]; 
}
@catch (NSException * e) {
     dispatch_async(dispatch_get_main_queue(), ^{
     [self.tableView reloadData];
     });
}

Any advise on how to reload tableview in case there's a fail within the update? thanks!

Update

So I can handle if the insertRowsAtIndexPaths:nil This works

@try {
    [self.tableView beginUpdates];
    //try with nil to go to catch block
    [self.tableView insertRowsAtIndexPaths:nil withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView endUpdates]; 
}
@catch (NSException * e) {
     [self.tableView endUpdates];
     dispatch_async(dispatch_get_main_queue(), ^{
     [self.tableView reloadData];
     });
}

However, the catch handler can't handle if the indexPath is -1 or out of bounds, and I'm getting this error: Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (60) must be equal to the number of rows contained in that section before the update (60), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).

This doesn't work

@try {
    [self.tableView beginUpdates];
    //try with nil to go to catch block
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:-1 inSection:0]] withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView endUpdates]; 
}
@catch (NSException * e) {
     [self.tableView endUpdates];
     dispatch_async(dispatch_get_main_queue(), ^{
     [self.tableView reloadData];
     });
}

The reason why I'm doing this is because I'm trying to debug this issue why this failed in the first place, but in the meantime, I want to recover from this issue and just refresh the table instead of crashing the app. Is there any way to undo insertRowsAtIndexPaths if it failed? Thanks in advance.

0条回答
登录 后发表回答