我有一个项目即将完成。当我将CloudKit记录下载到数组以显示在tableview中时,我的最后一个问题就出现了。这是我的控制器查询部分的代码。
for result in results!
{
let tablerestaurant = Restaurant()
if let name = result.value(forKey: "Name") as! String? {
tablerestaurant.name = name
}
// Do same for image
if let imageAsset = result.object(forKey: "Picture") as! CKAsset? {
if let data = try? Data(contentsOf: imageAsset.fileURL) {
tablerestaurant.image = UIImage(data: data)
}
}
self.tablerestaurantarray.append(tablerestaurant) // tablerestaurant is an array holding string and image instances of class Restaurant
self.restaurantArray.append(result) // restaurantArray holds CKRecords to be segued to the next controller
OperationQueue.main.addOperation( { () -> Void in
self.tableView.reloadData()
self.activity.isHidden = true
})}
这是我的cellForRowAtIndexPath Tablecell函数,缓存部分与全局数组一起注释
var tablerestaurantarray: [Restaurant] = []
let cache = NSCache<NSString, Restaurant>()
-
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "restaurantcell") as? RestaurantTableCell
/////////this is the cache portion//////////////
var oneRestaurant: Restaurant = tablerestaurantarray[indexPath.row]
if let cachedVersion = cache.Restaurant(forKey: "image")
{
oneRestaurant = cachedVersion
}
else
{
oneRestaurant = Restaurant()
cache.setObject(oneRestaurant, forKey: "image")
}
//////////////////////////
let restaurant: Restaurant = tablerestaurantarray[indexPath.row]
cell?.name?.text = oneRestaurant.name
// cell?.picture?.image = oneRestaurant.image
return cell!
我试图从这里https://www.hackingwithswift.com/example-code/system/how-to-cache-data-using-nscache复制这个简单的缓存程序,然后将其转录给我自己使用。但是,调试器声明了
NSCache<NSString, Restaurant> has no member Restaurant
它确实如此。所以我对我的问题感到很沮丧。你有想法吗?
更新2
var tablerestaurantarray: [Restaurant] = []
let cache = NSCache<NSString , Restaurant>()
var oneRestaurant: Restaurant = tablerestaurantarray[indexPath.row]
if let cachedVersion = cache.object(forKey: "image") { } //error is called here
{
oneRestaurant = cachedVersion
}
else
{
oneRestaurant = Restaurant()
cache.setObject(oneRestaurant, forKey: "image")
}