我正在尝试缓存一个Struct,这是我的代码:

class UserManager {
   static let sharedInstance : UserManager = UserManager()
   fileprivate let cacheKey = "currentUser" as AnyObject
   var currentUser: User? {
      didSet {
         self.cacheUser()
      }
   }

  fileprivate func getUserFromCache() -> User?{
     let cache = NSCache<AnyObject, AnyObject>()
       // here the user is always nil
     if let user = cache.object(forKey: cacheKey) as? User {
            return user
      }
      else {
        return nil
     }
  }

  fileprivate func cacheUser() {
     let cache = NSCache<AnyObject, AnyObject>()
     if let user = currentUser{
         cache.setObject(user  as AnyObject, forKey: cacheKey)
     }
     //Here : print user work fine and user is not nil
     print(cache.object(forKey: cacheKey) as? User)
  }

   init() {
      currentUser = getUserFromCache()
   }
}

问题在于,即使执行getUserFromCache()函数后,函数cacheUser返回的值始终为nil。

我的代码有什么问题?

最佳答案

每次调用cacheUser和getUser函数时,您都希望创建一个新的缓存,但您希望一个缓存不多。将其放在顶部的sharedInstance之后:

var cache = NSCache<AnyObject, AnyObject>()

并从cacheUser和getUser函数中删除let cache =...。

关于ios - Swift NSCache结构未正确保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42363234/

10-09 18:30