在新视图中的tableview中插入一行

我从一个带有一个部分的tableview开始,第一个部分总是有三行。 下载了一些内容后,我想在第二部分中显示一个新单元格,所以我这样做:

[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone]; 

但我得到一个NSInternalConsistencyException:

由于未捕获的exception’NSInternalInconsistencyException’而终止应用程序,原因:’无效更新:无效的节数。 更新后的表视图中包含的节数(2)必须等于更新前的表视图中包含的节数(1),加上或减去插入或删除的节数(插入0,0删除)。”

为什么不自动插入新的部分,如果我插入一个部分,那么在插入不在新部分中的行时会出现问题。

为什么不能自动添加新的部分? 当然,InsertRowAtIndexpath:还包括在必要时插入一个部分,因为NSIndexPath还包含一个部分。

 [self.tableView insertSections:nsIndexSetToInsert withRowAnimation:UITableViewRowAnimationAutomatic]; 

并且不要忘记相应地设置numberOfSectionsInTavleView和numberOfRowsInSection。

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. NSInteger numberOfSections; if (condition1) { numberOfSections = 2; } else if (condition2) { numberOfSections = 3; } else { numberOfSections = 4; } return numberOfSections; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section if(section == 1) return 3; else return numberOfRows; } 

在ViewDidLoad中保留它

 childArray1 = [[NSMutableArray alloc] initWithObjects: @"Apple", @"Microsoft", @"HP", @"Cisco", nil]; childArray2 = [[NSMutableArray alloc] init]; parentArray = [[NSMutableArray alloc] initWithObjects:childArray1, nil]; - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [parentArray count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSInteger rowCount ; if (section == 0) { rowCount = [childArray1 count]; } else { rowCount = [childArray2 count]; } return rowCount; } 

从服务器下载内容后。

  if([childArray2 count] > 0) [parentArray addObject : childArray2]; [tableView reloadData]; 

这应该适合你。