Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift cache tableview json data

I wonder if its possible to cache tableView JSON data?

In my VC I have this variable:

//Categories json data
var categories: JSON! = []

Then later inside a alamofire api call I get the json data and assign it like:

self.categories = JSON["catData"]
self.tableView.reloadData()

But is there any way to cache this data so I dont have to make a API call everytime?

like image 646
user2636197 Avatar asked Jul 05 '26 18:07

user2636197


1 Answers

You can create a singleton DataCache class where you can store all the data you want to cache. Prefer to store data inside a dictionary for specific key

class DataCache: NSObject {
    static let sharedInstance = DataCache()
    var cache = [String, AnyObject]()
}

Now in your api call, call this method

DataCache.sharedInstance.cache["TableViewNameKey"] = JSON["catData"]
self.categories = JSON["catData"] // Set this property for first time when you hit API

and in viewWillAppear(animated: Bool) method

if let lCategories = DataCache.sharedInstance.cache["TableViewNameKey"] {
    self.categories = lCategories
}
like image 194
Sahil Mahajan Avatar answered Jul 07 '26 08:07

Sahil Mahajan