【发布时间】:2017-03-31 23:42:28
【问题描述】:
我有一个列表,其中包含大约 8,500 个加载到 UITableView 中的项目,并且应该只有大约 200 个项目,其中 product.isnewitem 为真。对于每个“新”项目,应该加载一个图像(newicon.png),表明它是一个新项目;但是,当我开始向下滚动表格视图时,newicon 会显示在超过 50% 的项目上。所有项目都是通过 Realm 加载的。
新项目的检查在:
if product.isnewitem {
cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
}
这里是整个 cellForRowAtIndexPath 方法:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let paths = NSSearchPathForDirectoriesInDomains(documentsDirectory, userDomainMask, true)
let cell = tableView.dequeueReusableCell(withIdentifier: "ProductCell") as? OrderFormViewCell
?? UITableViewCell(style: .subtitle, reuseIdentifier: "ProductCell") as! OrderFormViewCell
let realm = try! Realm()
let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
let product = allProducts[indexPath.row]
cell.productDescriptionLabel.text = product.basedescription
queue.async {
let realm = try! Realm()
let allProducts = realm.objects(Product.self).sorted(byKeyPath: "basedescription")
let product = allProducts[indexPath.row]
if product.isnewitem {
cell.newIconImageView.image = #imageLiteral(resourceName: "newicon.png")
}
if let dirPath = paths.first {
let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("T\(product.itemno.replacingOccurrences(of: "-", with: "")).png")
if let image = UIImage(contentsOfFile: imageURL.path) {
cell.productImageView.image = image
}
else {
cell.productImageView.image = #imageLiteral(resourceName: "image-coming-soon.png")
}
}
}
return cell
}
【问题讨论】:
-
您不应该在
cellForRow(at:)中发出异步获取请求。单元格被重用,因此在提取完成时,单元格可能已被重用于另一行。如果项目不是新的,还要确保明确清除“新”图像。 -
@Paulw11 我还应该把异步调用放在哪里?我需要使用某种后台线程,以便 UI 不会滞后,并且我需要访问 IndexPath,因为每个产品图像对于每个单元格都是唯一的。应该改为同步调用吗?最后,“清除”“新”图像是什么意思?
标签: ios swift uitableview realm grand-central-dispatch