2

I have a ViewController that creates a new object and then back in the FirstViewController.m I have an unwind method that should update the tableView with a row for the new object. Using the reloadData method won't work because it reloads all of the cells which affects the methods I have in those cells. I would like to just add a new cell without reloading the entire tableView. My unwind method looks like this:

-(IBAction)unwind:(UIStoryboardSegue *)segue {
    ABCAddItemViewController *source = [segue sourceViewController];
    ABCItem *item = source.object;

    if (item != nil) {
        [self.objectArray addObject:item];

        [self.tableView reloadData];
    }
}

I've tried adding these lines instead of [self.tableView reloadData]:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.objectArray indexOfObject:item] inSection:0];
[self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];

However, the app crashes and I get this message:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), 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).

The number of rows in the tableView is determined by [self.objectArray count] in the numberOfRowsInSection: method.

How can I make this work? Or is there a better way?

Arnab
  • 4,216
  • 2
  • 28
  • 50
Benck
  • 515
  • 1
  • 5
  • 17
  • 1
    You have to update your data source (`self.objectArray`) with the additional data just before calling `insertRowsAtIndexPath`. – rmaddy Jun 17 '14 at 19:42
  • I tried to just replace the `[self.tableView reloadData]` line but that produces the error I mentioned. I add the object to the array right before then. – Benck Jun 18 '14 at 00:16
  • A call to `reloadData` will not give the error you posted. That would only be from the call to `insertRowsAtIndexPaths:`. BTW - you need to insert the row in the same location you add it to your array. – rmaddy Jun 18 '14 at 00:22
  • I can't use `reloadData` because reloading the entire table restarts some of the methods – Benck Jun 18 '14 at 18:38

1 Answers1

0

Error is saying your interface update expected 2 rows to display, but your data source only contains 1 row after update.

Is your "item" object an [NSNull null] value?

The line if(item != nil) can equate to true if item is an [NSNull null] value.

Could you try putting this extra check

if(item != nil && item != [NSNull null])
{
    ...
}

Or use a breakpoint and debugger to print out the value of item:

lldb> po item
Zhang
  • 11,549
  • 7
  • 57
  • 87