swift 3 NSCache不起作用

ppr*_*lon 12 swift

我目前升级到Swift 3.0.我无法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()
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

bee*_*ven 37

NSCache 在Swift 3.0中更加Swifty.

它表现得像swift Dictionary,你需要给出类型KeyValue:

let imageCache = NSCache<NSString, UIImage>()
Run Code Online (Sandbox Code Playgroud)

  • 唉,不太适合我的口味; 你还是不能使用Swift String :( (6认同)