Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView: delete not visible rows

My question is about deleting "invisible" rows in a UITableView. When I say invisible, I mean rows that are not showed on the screen. For example, all the rows that aren't returned by calling the UITableView method - (NSArray *)visibleCells.

I'm asking this because I'm developping an "expandable" UITableView. A little bit like a tree. You can have a table like this :

  • Menu 1
    1. Menu 1.1
    2. Menu 1.2
  • Menu 2
    1. Menu 2.1
    2. Menu 2.2

And when you click on "Menu 1" the cells "Menu 1.1" and "Menu 1.2" will either appear or disappear. I do this by simply inserting or deleting cells with an animation.

The problem is, if I have long menus and the user scrolls, if half the rows from "Menu 1", for instance, ar hidden (not visible, not showed on the screen, visible only if you scroll down) and that the user wants to reduce "Menu 1" this will cause my application to crash because I'm trying to delete rows that are not visible.

The actual error message is :

* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (11) must be equal to the number of rows contained in that section before the update (15), plus or minus the number of rows inserted or deleted from that section (0 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

If I do the exact same manipulation with all the rows visible, no problem with the app and the menu behaves correctly.

like image 921
Starscream Avatar asked Nov 13 '22 04:11

Starscream


1 Answers

On your tableview update calls, you need to update the tableview data source as well as the tableview. You can use UITableView's indexPathsForVisibleRows method to find the positions in which to remove the objects from the source, and update your table.

like image 116
J2theC Avatar answered Nov 15 '22 10:11

J2theC