ios - 为 UITableViewCell 创建了图像缓存,但只显示一张图像

标签 ios swift caching uitableview

我在为 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:

Results from the added breakpoint

最佳答案

您对不同的对象使用相同的 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/

相关文章:

ios - 将 UITextView 的高度放在 CGFloat 变量中

ios - 条件语句中的守卫

caching - Gitlab CI 和 .NET Core - 无法通过 2 阶段构建获取 nuget 缓存

objective-c - 如何在iPhone中更改UITextField的颜色?

ios - 在 Swift 中获取 UITapGestureRecognizer 的发送者

swift - 为 "If"语句测试值设置多个整数

swift - iOS 10 使用参数返回导航堆栈中的根目录

java - cache2k cachesource 使用 mysql 作为后端

php - WooCommerce: header 中的迷你购物车似乎已缓存

ios - 将 tableView 单元格展开和折叠到标签的文本