使用NSCache缓存自定义类

时间:2017-09-01 17:54:22

标签: ios swift caching memory

我正在尝试缓存我的自定义类,以便在用户离线时重新加载它。我是Swift的新手所以我一直在寻找,大多数人都说使用NSCache。我在课堂上使用过这种方法但是它起作用了。

let cache = NSCache<NSString, ShopProfileModel>()
let myObject: ShopProfileModel

if let cachedVersion = cache.object(forKey: "CachedObject") {
    // use the cached version
    myObject = cachedVersion
    print("Object has been cached")
} else {
    // create it from scratch then store in the cache
    myObject = self.shopProfileModel
    cache.setObject(myObject, forKey: "CachedObject")
    print("Object has not been cached")
}

它始终打印“对象尚未缓存”。知道为什么我的对象没有缓存吗?

0 个答案:

没有答案