views:

32

answers:

1

So I'm updating a tableview by inserting/deleting/reloading rows as needed, but, as I'm not 100% confident that the tableview will always update correctly, is there any way to fail safely from a bad batch of updates?

Right now, I have this:

    // Try to animate the updates. If something goes wrong, just reloadData.
    @try {
        [tableView beginUpdates];
        [tableView deleteRowsAtIndexPaths:deleteArray withRowAnimation:UITableViewRowAnimationMiddle];
        [tableView reloadRowsAtIndexPaths:reloadArray withRowAnimation:UITableViewRowAnimationNone];
        [tableView insertRowsAtIndexPaths:insertArray withRowAnimation:UITableViewRowAnimationMiddle];
        [tableView endUpdates]; 
    }
    @catch (NSException * e) {
        if([[e name] isEqualToString:NSInternalInconsistencyException]){    
            [tableView reloadData];
            NSLog(@"animation failed, just reloading data");
        }
        else {
            @throw e;
        }
    }

However, once it hits that exception, reloadData seems to not work. Is there any other way to basically reset the UITableView into a working state?

+1  A: 

More ideally you should be backing the table with an array that's guaranteed to do what the table expects it to do. UIKit expects exceptions to be fatal (this holds with Apple's philosophy that exceptions indicate programmer error.)

cobbal
Yes, that would be extremely ideal. I don't mean to sound snide, but ideally everything would work out fine and nothing would go wrong. Unfortunately, that rarely ever happens. And in production code, I would much rather it fail safely instead of crashing the app in the user's face.
David Liu
@David well, if you're absolutely set on recovering. I would catch the exception, then recreate the table view. Know that this will almost certainly leak some memory and may leave other things in undesirable states.
cobbal