我在为 cellForRowAtIndex
中的 UITableViewCell
创建功能图像缓存方面得到了很大帮助。不幸的是,使用下面的代码,只一遍又一遍地显示一张图像。我的印象是,cellForRowAtIndexPath
就像一个 for 循环,为每个行
再次运行。因此,我想知道为什么只显示一张图像。
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantcell") as? RestaurantTableCell
var oneRestaurant: Restaurant = tablerestaurantarray[indexPath.row]
if let cachedVersion = cache.object(forKey: "image") {
oneRestaurant = cachedVersion
} else {
cache.setObject(oneRestaurant, forKey: "image")
}
cell?.picture?.image = oneRestaurant.value(forKey: "image") as! UIImage?
let restaurant = restaurantArray[indexPath.row]
cell?.name?.text = restaurant.value(forKey: "Name") as? String
return cell!
}
更新2:
最佳答案
您对不同的对象使用相同的 NSCache 键("image"
)。这就是为什么只有第一个 Restaurant
对象被保存到缓存中。对于所有其他单元格,您将查找为键 "image"
缓存的对象,并获取之前保存的相同的 Restaurant
对象。
您必须使用不同的键来缓存不同的 Restaurant
对象。尝试将索引路径附加到缓存键:
let key = "restaurant \(indexPath)"
if let cachedVersion = cache.object(forKey: key) {
oneRestaurant = cachedVersion
} else {
cache.setObject(oneRestaurant, forKey: key)
}
我不太明白为什么你想缓存餐厅对象。您已经将它们放在 tablerestaurantarray
中,因此缓存它们不会有任何好处。也许您的意图是缓存图像?
关于ios - 为 UITableViewCell 创建了图像缓存,但只显示一张图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42177267/