【问题标题】:Created an image cache for a UITableViewCell but only one image is displayed为 UITableViewCell 创建了一个图像缓存,但只显示一个图像
【发布时间】:2017-06-29 20:34:30
【问题描述】:

在为cellForRowAtIndex 中的UITableViewCell 创建功能性图像缓存方面,我得到了很大帮助。不幸的是,使用下面的代码,只能一遍又一遍地显示一张图像。我的印象是 cellForRowAtIndexPath 就像一个 for 循环,为每个 row 再次运行。因此,我想知道为什么只显示一张图片。

 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:

Results from the added breakpoint

【问题讨论】:

  • 单元格有多高?故事板中的默认图像是什么?据我了解,您可以从Restaurant 类中获得图像。你能把那门课也发一下吗?
  • 只是一个简单的“var image = UIimage?”为班级。

标签: ios swift uitableview caching tableviewcell


【解决方案1】:

您对不同的对象使用相同的 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 中拥有它们,因此缓存它们不会有任何好处。也许您的意图是缓存图像?

【讨论】:

  • 这些图像是从云套件下载的,并且 tableview 动画在创建缓存之前一直不稳定.. 或者至少这是我的想法。
  • 我应该补充一下,ckrecords的图像是通过一个类来接收图像数据的。
  • 不幸的是,建议的“let key = 'restaurant (indexpath)”不起作用。
  • 您能否检查一下 oneRestaurant 是否为每个餐厅对象保存到缓存中一次?在 else 子句中设置断点。
  • 另外,请确保您没有错字:它应该是“restaurant (indexPath)”,而不是“restaurant (indexpath)”。请注意评论中缺少的“\”以及小写的“p”。这个想法是像这样将当前索引路径添加到键中:“restaurant [0, 2]”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多