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

Results from the added breakpoint

+0

细胞有多高?什么是故事板中的默认图像?根据我的理解,您可以从“餐厅”类获得图像。你可以发布该课程吗? –

+0

只是一个简单的“var image = UIimage?”为班级。 – Jon

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

+0

这些图像是从云端工具包下载的,桌面视图动画波涛汹涌,直到创建缓存。或者至少这是我的想法。 – Jon

+0

我应该补充说,ckrecords的图像是通过一个类来接收图像数据的。 – Jon

+0

建议“let key ='restaurant \(indexpath)”不幸运。 – Jon