NSCache无法正常工作,无法从缓存加载图像

时间:2018-04-15 11:57:15

标签: ios swift xcode caching networking

由于NSCache已更改为泛型类型NSCache Now,因此这是我正在执行的代码段 然而,控制台正在打印 - “After Image To Cache”&调度主队列CustomImageView但是执行的缓存中的图像没有显示在那里!!也许它没有存储在我正在创建的缓存中!有帮助吗?将不胜感激

let imageCache = NSCache<AnyObject, AnyObject>()

类CustomImageView:UIImageView {     var imageURLString:String?

func loadImageUsingURlString(urlString: String)
{
    imageURLString = urlString

    let url = URL(string: urlString)

    image = nil
    if let imageFromCache = imageCache.object(forKey: urlString as AnyObject ) as? UIImage
    {
        self.image = imageFromCache
        print("Image From Cache Executed")
        return
    }



    URLSession.shared.dataTask(with: url!, completionHandler:
    {
        (data, response, error) in

        if error != nil
        {
            print(error ?? "loadImageUsingURlString | Class : Helpers -> CustomImageView")
            return
        }

        DispatchQueue.main.async
        {
            let imageToCache = UIImage(data: data!)
            print("After Image To Cache")


            if self.imageURLString == urlString
            {
                print("Dispatch Main Queue CustomImageView[![enter image description here][1]][1]")
                self.image = imageToCache

            }
            else
            {
                        imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
            }



        }

    }).resume()
}

}

2 个答案:

答案 0 :(得分:0)

首先:

let imageCache = NSCache<AnyObject, AnyObject>()为什么您在此使用AnyObject而不是您正在使用的类型StringUIImage。您在代码中有不必要的转换。

第二个想法:

if self.imageURLString == urlString
            {
                print("Dispatch Main Queue CustomImageView[![enter image description here][1]][1]")
                self.image = imageToCache

            }
            else
            {
                        imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)
            }

如果网址匹配,则不会缓存图片。您应该删除else并让imageCache.setObject(imageToCache!, forKey: urlString as AnyObject)始终在异步调用后执行。

顺便说一下,总是使用更好的开发人员编写和测试过的代码:) 试试这个:Kingfisher

答案 1 :(得分:0)

我认为if self.imageURLString == urlString条件不是必需的,您能否尝试下面的代码,它对我来说是完美的?

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func loadImageCacheWithUrlString(urlString: String) {

        if let cachedImage = imageCache.object(forKey: urlString as NSString){
            self.image = cachedImage
            return
        }

        URLSession.shared.dataTask(with: URL(string: urlString)!) { (data, response, error) in
            if error != nil {
                return
            }
            DispatchQueue.main.async {
                if let downloadedImage = UIImage(data: data!) {
                    imageCache.setObject(downloadedImage, forKey: urlString as NSString)
                    self.image = downloadedImage
                }
            }
            }.resume()
    }
}