I have a project I'm close to completing. My last problem arises when I've downloaded CloudKit records to an array to be displayed in a tableview. Here is my code for the query portion of the controller.
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
})}
and here is my cellForRowAtIndexPath Tablecell function, with the cache portion commented along with the global arrays here
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!
I've attempted to copy this simply cache procedure from here https://www.hackingwithswift.com/example-code/system/how-to-cache-data-using-nscache and transcribe it towards my own use. However, the debugger states that
NSCache<NSString, Restaurant> has no member Restaurant
which it does. So I'm lost as to my problem. Would you have an idea?
Update 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")
}