How to add rows to a table section? There is such a code

NSInteger rowIndex = [dictID allValues].count; NSInteger setcionIndex = arraySection.count; [weakSelf.tableView beginUpdates]; [weakSelf.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:rowIndex inSection:setcionIndex]] withRowAnimation:UITableViewRowAnimationAutomatic]; [weakSelf.tableView endUpdates]; It gives me the error 'attempt to insert row 3 into section 2, but there are only 2 sections after the update'!

    2 answers 2

    I understand that you are trying to add a row to the last section, then you just need to select the correct section.

     NSInteger setcionIndex = arraySection.count - 1; 

    If you want to add a section, then you also need to add a section.

     [weakSelf.tableView insertSections:[NSIndexSet indexSetWithIndex:arraySection.count] withRowAnimation:UITableViewRowAnimationAutomatic]; 

    The addition and animation code is correct, but after [weakSelf.tableView beginUpdates]; it is also necessary to update the datasource, since at the moment [weakSelf.tableView endUpdates]; the axis will call numberOfSectionsInTableView and all numberOfRowsInSection and it expects that now these methods will return data that already contains the rows that you added.

    • one
      I can not understand the update datasource. Shove data parsing after [weakSelf.tableView beginUpdates] ? Now parsing is done before. I did as you advised, anyway the same mistake is made, probably because of the datasource update. - Seryozha Kvyatkovsky
    • The datasource update refers to updating the data used to populate the table, yes, this update can be done before, but classically, if there is a begin / endUpdates, then the datasource is modified inside, in parallel with the table, but if updates are made to the table the same method - you can not bother. It is important that the datasor updates coincide exactly with the table update commands, that is, the rows are added / deleted in the corresponding sections, the same with the sections. Show how datasors look like? I don't understand where rowIndex comes from - markov
    • [responseObject[@"filmsData"] enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { [array addObject:obj[@"id"]]; [dictID setValue:array forKey:[KSDate convertYandexDateToStringDate:responseObject[@"date"]]]; }]; Parsy data from the response from the server. dictID dictionary. All this is done in the AFHTTPSessionManager block when I make a get request. - Seryozha Kvyatkovsky
    • And numberOfSectionsInTableView and numberOfRowsInSection? - Markov
    • I just see that arraySection is not used with this update at all - markov

    The number of cells must match what is returned in the datasource method. Otherwise there will be a fall. See where you do not match. Or write more code.