Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I get the exception:

Invalid update: invalid number of sections. The number of sections contained in the table view after the update (2) must be equal to the number of sections contained in the table view before the update (1), plus or minus the number of sections inserted or deleted (1 inserted, 1 deleted).

This is what my number of sections function looks like.

func numberOfSections(in tavleView: UITableView) -> Int {
    let someArray = someFunctionToRetrieveArrayFromUserDefaults()
    return someArray.count 

The array is a decoded array retrieved from the UserDefaults. An encoded array is written to the UserDefaults every time a new value is added so it is always up to date.

Can anyone please help provide clarity on the exception and what I am doing wrong?

As mentioned, the number of inserted (1) + deleted (1) is 1 - 1 = 0, whereas you're returning the value 2 (someArray.count is 2). Did you use peformBatch? insert/delete rows?

Why does it happen? it's hard to know from the very short code example you've provided, I'm assuming your array is not thread safe (you've mentioned decoding from UserDefaults), therefore by the time numberOfSections is called, the data is not synchronised yet.

Try to make a simpler someArray not accessing UserDefaults, and make your code run without crashing.

Sorry for the brevity of the code, it's company code and it's huge so I have to simplify it. I tried modifying the data source so it takes from an array of a singleton class object (no encoding/decoding) but the problem persists. Any other ideas? – justanintern Jan 19, 2022 at 10:41 can you at least present the code that triggers that tableView reload? do you add/insert rows? do you use performBatch? – Maor Atlas Jan 19, 2022 at 10:43 I found my mistake and it was that the tableview.reload wasn't called. Thanks for pointing me towards the direction. – justanintern Jan 19, 2022 at 11:39

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.