TableView app terminated due to 'NSInternalInconsistencyException'

后端 未结 2 634
暗喜
暗喜 2020-12-30 12:49

I\'m trying to get the hang of UITableViews and everything that goes with it. At the moment I have the following code:

- (NSInteger)tableView:(UITableView *)         


        
相关标签:
2条回答
  • 2020-12-30 13:04

    It's pretty easy, the problem lies here:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        return 10; 
    }
    

    The delegate pattern used by apple, means that you're the one responsible on managing the content of the UITableView through its delegates, meaning that, if you delete a row, you're also responsible of deleting the data from the data model.

    So, after deleting a row, it would make sense that the number of rows in section would decrease to "9", yet, your function is always returning 10, and thus throwing the exception.

    Typically, when using an table, and the contents will change, an NSMutableArray is pretty common, you do something like this:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return [arrayWithStuff count];
    }
    

    And then, deleting an object (removeObjectAtIndex:) from the array would automatically update the number of rows.

    (Edit: Replied at about the same time as Mike Hay, try following his advice too! I skipped the begin/end Update, because it seems you already read about it)

    0 讨论(0)
  • 2020-12-30 13:06

    Tobias, what you need to do when deleting rows is

    // tell the table view you're going to make an update
    [tableView beginUpdates];
    
    // update the data object that is supplying data for this table
    // ( the object used by tableView:numberOfRowsInSection: )
    [dataArray removeObjectAtIndex:indexPath.row];
    
    // tell the table view to delete the row
    [tableView deleteRowsAtIndexPaths:indexPath 
               withRowAnimation:UITableViewRowAnimationRight];
    
    // tell the table view that you're done
    [tableView endUpdates];
    


    When you call endUpdate the number returned from tableView:numberOfRowsInSection: must be the same as the number at beginUpdate minus the number of rows deleted.

    0 讨论(0)
提交回复
热议问题