views:

402

answers:

1

I have a UITableView that I am loading via JSON. So my logic goes like this:

  1. Fetch the JSON (NSOperation, calling back to main thread)
  2. In callback, parse the json, and insert new data into my table's data source array.
  3. Call reloadData on the TableView to show the new data.

My question is: How can I ANIMATE the arrival of new rows in the table? Right now I just have them all popping into existence at once, and what I want to do is make them animate into place, because that looks way cooler.

I think what I want is to use:

 [self.theTableView insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationRight];

But that gives me runtime complaints about the size of the update being different than the size in the data source.

Am I missing something about how that method should be used? Does anyone know of an example where somebody is animating new rows into a TableView via this pattern?

Update: Basically, I solved this thanks to Ben's guidance, with the following approach:

  1. Start with [self.theTableView beginUpdates];
  2. When I loop over my entries in the JSON, insert them at the beginning of my array, incrementing their index each time through the loop.
  3. Call insertRowsAtIndexPath each time through the loop, like this:

    NSIndexPath *indexPath; indexPath = [NSIndexPath indexPathForRow:[self.theChatEntries indexOfObject:message] inSection:0]; [self.theTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:NO];

  4. End with endUpdates outside of the loop.

Woot.

A: 

You're on the right track; you need to wrap your calls to -insertRowsAtIndexPaths:withRowAnimation: with a [self.theTableView beginUpdates] and [self.theTableView endUpdates].

Ben Gottlieb
I tried that but when I get the very first row from the JSON, it crashes with this: '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 (0), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted).'
Genericrich
Accepted for steering me on the right track. Updating the question for posterity. Thanks!
Genericrich