简体   繁体   中英

iOS application crashes when trying to insert new row in UITableView

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:YES];
[self.tableView endUpdates];

This piece of code crashes my iOS application and returns the following error:

Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (0) 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 (1 inserted, 0 deleted).

Can someone tell me why? And how come it says that the number of rows after the update is zero, when it at the same time says 1 inserted , 0 deleted ?

Update

The code above gets triggered when I receive a push notification during runtime. When that happens, the delegate adds the received data to a dictionary stored in a .plist file (which the table view uses to populate its cells with) followed by a call to a custom method in the RootViewController, where the table view is located. This method executes the code above followed by a crash. However, when I log [theDictionary count] in - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section the number increments just as it should right before crashing.

Also worth noting is that when i log self.tableview I receive a different "memory address" from the RootViewController when it loads upon launch, and when receiving a push notification. Maybe this has something to do with it?

This is my - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section method:

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

And a picture of the error:

错误

The numberOfRowsInSection method should return the correct number of rows whenever you make any change to the data source of table view.

For example if the total number of rows in the table is 5 and if you are going to add one more row, then the numberOfRowsInSection method should return 6.

Its easily achieved by having the data in an array or dictionary . If you want to add or delete rows just update the array or dictionary. And just return [array count] or [dictionary count] from numberOfRowsInSection method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM