简体   繁体   中英

Invalid update: invalid number of sections when doing TableView.reloadData()

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.

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