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

Created an image cache for a UITableViewCell but only one image is displayed

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

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