快速删除元素字典并重新加载表视图



我在CoreData中有一个字典和产品:

var productSortArray: [Date:[Product]?] = [:]
var productArray = [Product]()

这是我的行数部分:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (productSortArray[dateArray[section]]!!.count)
}

当我删除提交编辑样式中的行时,我更新:

self.productArray.remove(at: indexPath.row)                
tableView.deleteRows(at: [indexPath], with: .automatic)
tableView.reloadData()

但是,当删除行并重新加载表时,行数不正确并且存在问题:

更新后现有节中包含的行数 (1( 必须等于更新前该节中包含的行数 (1(,加上或减去从该节插入或删除的行数(0 插入,1 删除(,加上或减去移入或移出该节的行数(0 移入, 0 搬出(。

而不是处理数组和字典,如果你创建实际表示你的数据的对象,你会发现它会容易得多......

struct ProductSection {
let date: Date
var products: [Product]
}
var sections: [ProductSection] = // Initialise this

然后

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].products.count 
}


然后删除一行...

sections[indexPath.section].remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .fade)

最新更新