我想知道是否可以缓存tableview json数据?
在我的VC中,我有此变量:
//Categories json data
var categories: JSON! = []
然后在Alamofire API调用中,我获取JSON数据并分配:
self.categories = JSON["catData"]
self.tableView.reloadData()
但是有什么方法可以缓存此数据,因此我不必每次都进行API调用?
您可以创建一个Singleton Datacache类,您可以在其中存储要缓存的所有数据。更喜欢将数据存储在特定键的字典中
class DataCache: NSObject {
static let sharedInstance = DataCache()
var cache = [String, AnyObject]()
}
现在在您的API调用中,调用此方法
DataCache.sharedInstance.cache["TableViewNameKey"] = JSON["catData"]
self.categories = JSON["catData"] // Set this property for first time when you hit API
和viewWillAppear(animated: Bool)
方法
if let lCategories = DataCache.sharedInstance.cache["TableViewNameKey"] {
self.categories = lCategories
}
可以将SwiftlyCache用于数据缓存。您可以直接缓存符合代码协议的数据。非常方便。如果需要,可以尝试https://github.com/hlc000000/swiftlycache