为UITableViewCell创建图像缓存,但只显示一个图像
问题描述:
我在为中的UITableViewCell
创建功能图像缓存方面有很大的帮助。不幸的是,下面的代码,只有一个图像反复显示。我的印象是,cellForRowAtIndexPath
就像是for循环,每次运行row
。因此,我想知道为什么只显示一个图像。为UITableViewCell创建图像缓存,但只显示一个图像
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
中拥有它们,所以缓存它们不会有任何好处。也许你的意图是缓存图像?
细胞有多高?什么是故事板中的默认图像?根据我的理解,您可以从“餐厅”类获得图像。你可以发布该课程吗? –
只是一个简单的“var image = UIimage?”为班级。 – Jon