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

标签 ios swift xcode caching networking

由于 NSCache 已更改为泛型类型 NSCache 现在,这就是我正在执行的代码片段 但是,控制台正在打印 -“图像到缓存后”并调度主队列 CustomImageView,但执行的缓存中的图像没有显示在那里!也许它没有存储在我正在创建的缓存中!有什么帮助吗?将不胜感激

let imageCache = NSCache<AnyObject, AnyObject>()

类 CustomImageView:UIImageView { var imageURLString : 字符串?

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()
}

}

最佳答案

首先:

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)
            }

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

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

关于ios - NSCache 无法正常工作,无法从缓存加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49841633/

相关文章:

swift - 将用户名作为 NavBar Item

xcode - 错误 "Thread 1: breakpoint 2.1"

IOS - 如何修复 "ld: library not found for -lBolts"错误?

ios - 以编程方式加载另一个 View 需要时间

iOS - UITableViewCell 中文本周围的圆角矩形,如 Things 应用程序

ios - 将纯 Swift 自定义框架导入其他 Swift 项目

c++ - VLCKit与iOS项目中的.mm文件冲突

ios - 单个 View 的多个手势响应器

ios - 如何使用 Sheets API v4 在 Swift 4 中创建新的 Google 表格

swift - 如何快速使用 CFURLCreateFromFileSystemRepresentation ?