Jon
Jon

Reputation: 85

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

I've had a great help in creating a functional image cache for a UITableViewCell in cellForRowAtIndex. Unfortunately, with the code below, only one image is displayed over and over. I was under the impression that cellForRowAtIndexPath was like a for loop, running again for each row. Therefore, I'm wondering why only one image is displayed.

 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!
}

Update 2:

Results from the added breakpoint

Upvotes: 0

Views: 540

Answers (1)

nils
nils

Reputation: 1976

You use the same NSCache key ("image") for different objects. That's why only the first Restaurant object is saved into the cache. For all other cells you look for the object cached for key "image" and get the same previously saved Restaurant object back.

You have to use different keys for caching different Restaurant objects. Try to append the index path to the cache key:

let key = "restaurant \(indexPath)"

if let cachedVersion = cache.object(forKey: key) {
    oneRestaurant = cachedVersion
} else {
    cache.setObject(oneRestaurant, forKey: key)
}

I don't quite understand why you want to cache restaurant objects though. You already have them in the tablerestaurantarray, so there won't be any benefit caching them. Maybe your intention was caching the images?

Upvotes: 1

Related Questions