Search code examples
objective-cios5xcode4

Why is this iOS ViewController action kicking up an exception?


I have a Bar Button Item in one of my screens. The button should trigger the addItem action in my ViewController when pressed.

- (IBAction)addItem
{

    // items is an Array storing list items
    int newRowIndex = [items count];

    ChecklistItem *item = [[ChecklistItem alloc] init];
    item.text = @"I am a new row";
    item.checked = NO;
    [items addObject:item];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:newRowIndex inSection:0];
    NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
    [self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
}

When I press the button the application terminates and raises this exception:

GNU gdb 6.3.50-20050815 (Apple version gdb-1708) (Thu Nov  3 21:59:02 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB.  Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".Attaching to process 1799.
2012-02-08 16:04:08.146 Checklists[1799:f803] *** Assertion failure in -[_UITableViewUpdateSupport _computeRowUpdates], /SourceCache/UIKit_Sim/UIKit-1912.3/UITableViewSupport.m:386
2012-02-08 16:04:08.149 Checklists[1799:f803] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid table view update.  The application has requested an update to the table view that is inconsistent with the state provided by the data source.'
*** First throw call stack:
(0x13bb052 0x154cd0a 0x1363a78 0x99b2db 0x26eb49 0x27c0e3 0x95e3a 0xa182a 0xa1869 0x2e7d 0x13bcec9 0x155c2 0x250d54 0x13bcec9 0x155c2 0x1555a 0xbab76 0xbb03f 0xba2fe 0x3aa30 0x3ac56 0x21384 0x14aa9 0x12a5fa9 0x138f1c5 0x12f4022 0x12f290a 0x12f1db4 0x12f1ccb 0x12a4879 0x12a493e 0x12a9b 0x1ec8 0x1e25)
terminate called throwing an exceptionsharedlibrary apply-load-rules all
Current language:  auto; currently objective-c

Can anyone explain why this exception is being raised?


Solution

  • Before you attempt to insert new rows, you must prepare the table for updates:

    [[self tableview] beginUpdates];
    
    [[self tableview] insertRowsAtIndexPaths ...
    
    [[self tableview] endUpdates];
    

    Additionally, it is important that your:

    -(void)tableView:(UITableView *)tableview numberOfRowsInSection
    

    Return the most-up-to-date quantity of rows at the time you call:

     [tableview endUpdates];
    

    Assuming that the numberOfRows method only returns a count of objects in your items array, you should be fine...