首页 > 解决方案 > 在主线程上重新加载表部分时出现 Swift NSInternalInconsistencyException

问题描述

我有一个UITableView间接访问它的数据(即它由指针的数据结构支持)并且每当从远程服务器中提取新数据时异步重新加载它的部分。看来我的重新加载计划有一个竞争条件;即使我只在主线程上执行我的表视图重新加载,我偶尔会看到以下错误:

由于未捕获的异常“NSInternalInconsistencyException”而终止应用程序,原因:“无效更新:第 1 节中的行数无效。更新 (1) 后现有节中包含的行数必须等于该节中包含的行数更新前的节 (0),加上或减去从该节插入或删除的行数(0 插入,0 删除),加上或减去移入或移出该节的行数(0 移入,0 移动出去)。'

我的代码结构如下:

var table_data_indirect_1: [CustomDataPointer] = []
var table_data_indirect_2: [CustomDataPointer] = []

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let x = customData(in: indexPath.section)[indexPath.row], let cell = table.dequeueReusableCell(withIdentifier: "custom-identifier", for: indexPath) as? CustomCell {
        cell.setCustomData(to: x)
        return cell
    } else {
        return UITableViewCell()
    }
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return customData(in: section).count
}

 func numberOfSections(in: UITableView) -> Int {
    return 2
}

func customData(in section: Int) -> [CustomDataStruct] {        
    switch section {
    case 0:
        return table_data_indirect_1.map { asyncLoadCustomData($0, for: section) }
    case 1:            
        return table_data_indirect_2.map { asyncLoadCustomData($0, for: section) }
    default:
        return []
    }
}

func asyncLoadCustomData(_ customDataPointer: CustomDataPointer, for section: Int) -> CustomDataStruct {
    if customDataPointer.isLoaded {
        return customDataPointer.backingStruct
    } else {
        customDataPointer.asyncLoad { result in
            DispatchQueue.main.async { [weak self] in
                let section_set = IndexSet(integersIn: section...section)
                self?.table.reloadSections(section_set, with: .none)
            }
        }
        return customDataPointer.placeholderStruct
    }
}

标签: iosswiftuitableviewasynchronousgrand-central-dispatch

解决方案


推荐阅读