简体   繁体   English

无效更新:执行 TableView.reloadData() 时的节数无效

[英]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).更新后表视图中包含的节数(2)必须等于更新前表视图中包含的节数(1),加上或减去插入或删除的节数(1插入,1已删除)。

This is what my number of sections function looks like.这就是我的部分 function 的样子。

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

The array is a decoded array retrieved from the UserDefaults.该数组是从 UserDefaults 检索的解码数组。 An encoded array is written to the UserDefaults every time a new value is added so it is always up to date.每次添加新值时,都会将编码数组写入 UserDefaults,因此它始终是最新的。

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).如前所述,插入 (1) + 删除 (1) 的数量为 1 - 1 = 0,而您返回的值为 2(someArray.count 为 2)。 Did you use peformBatch?你用过 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.从您提供的非常短的代码示例中很难知道,我假设您的数组不是线程安全的(您已经提到从 UserDefaults 解码),因此在调用 numberOfSections 时,数据尚未同步。

Try to make a simpler someArray not accessing UserDefaults, and make your code run without crashing.尝试制作一个不访问 UserDefaults 的更简单的 someArray,并使您的代码运行而不会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM