2016-09-18 109 views
9

我目前升级到swift 3.0我无法让NSCache在下面工作是我目前拥有的代码。我没有看到任何我错过我不知道我到底做了什么错。提前谢谢你swift 3 NSCache不起作用

class myClass { 
    let imageCache = NSCache() 

    func downloadImageByUserId(userId:String,imageView:UIImageView){ 

     print(userId) 
     fireBaseAPI().childRef("version_one/frontEnd/users/\(userId)").observeEventType(.Value, withBlock: {snapshot in 
      let imageUrl = snapshot.value!["profileImageUrl"] as! String 

      // check image cache 
      print(self.imageCache.objectForKey(imageUrl)) 
      if let cacheImage = self.imageCache.objectForKey(imageUrl) as? UIImage{ 
       print("image cache") 
       imageView.image = cacheImage 
       return 
      } 
      print("image not cache") 
      //retrieve image 
      let url = NSURL(string: imageUrl) 

      NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, resposn, error) in 
       if error != nil { 
        print(error) 
        return 
       } 

       dispatch_async(dispatch_get_main_queue(),{ 
        if let downloadImage:UIImage = UIImage(data: data!){ 
         self.imageCache.setObject(downloadImage, forKey: imageUrl) 
         imageView.image = downloadImage 
        } 
       }) 

      }).resume() 
     }) 
    } 
} 
+2

你确定它斯威夫特3之前工作过吗?除非我弄错了,否则每次调用方法时,都会在'let imageCache = NSCache()'中创建一个新的* empty *缓存。 –

+0

@MartinR我检查并在方法外放置了'let imageCache = NSCache()'。它也看起来像缓存工作,只有当它在'NSUrlSession'里面后,它变成'nil'我不确定'.resume'与它有什么关系。请看修改问题。 – pprevalon

回答

27

NSCache更Swifty在Swift 3.0。

它的作用类似于快捷Dictionary,你需要给的KeyValue类型:

let imageCache = NSCache<NSString, UIImage>()