Michael
Michael

Reputation: 811

ReloadData after UITableView updates

I'm trying to add rows to my tableView like this:

[myArray addObject:@"Apple"];

[myTableView beginUpdates];
[myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
[myTableView endUpdates];

The problem is that the cells don't get refreshed. The textLabels do no correspond to the datasource array.

I fix the problem by adding:

[myTableView reloadData];

but that makes the nice insertion animation go away.

Ideas? Thanks!

Upvotes: 1

Views: 415

Answers (2)

Stephen Darlington
Stephen Darlington

Reputation: 52565

addObject: adds an object to the end of a mutable array. Then, on your next line, you tell the table view that there's a new row to display at the very top of the table. Unless you have your array "backwards," it looks as though you're telling the table to "insert" a cell in the wrong place.

Upvotes: 4

jjv360
jjv360

Reputation: 4140

You're adding the item to the end of the array, but adding a row to the beginning of the table... Try it like this:

NSString* obj = @"Apple";
[myArray addObject:obj];

[myTableView beginUpdates];
[myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:[myArray indexOfObject:obj] inSection:0]] withRowAnimation:UITableViewRowAnimationTop];
[myTableView endUpdates];

Upvotes: 1

Related Questions