Ios 缓存无法保存tableView单元格图像

Ios 缓存无法保存tableView单元格图像,ios,swift,uitableview,cell,nscache,Ios,Swift,Uitableview,Cell,Nscache,我正在尝试将图像保存在缓存中,这样当我上下滚动时,它就不必再次下载这些图像。不幸的是,这似乎不起作用,因为当我滚动网络活动时,所有的图像都被下载了。有什么想法吗 let cache = NSCache<NSString, UIImage>() override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { le

我正在尝试将图像保存在缓存中,这样当我上下滚动时,它就不必再次下载这些图像。不幸的是,这似乎不起作用,因为当我滚动网络活动时,所有的图像都被下载了。有什么想法吗

 let cache = NSCache<NSString, UIImage>()

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: idForCell, for: indexPath)

        let usr = userList[indexPath.row]
        cell.textLabel?.text = usr.name
        cell.detailTextLabel?.text = usr.email

        if cell.imageView?.image != nil{
            return cell
        }

        let key = NSString(string: usr.imgUrl!)

        if cache.object(forKey: key) != nil{
            cell.imageView?.image = cache.object(forKey: key)! as UIImage
            return cell
        }

        if let imgUrl = usr.imgUrl{
            let url = NSURL(string: imgUrl)
                URLSession.shared.dataTask(with: url as! URL, completionHandler: { (data, resp, err) in
                    if err != nil{
                        print(err!)
                        return
                    }

                    DispatchQueue.main.async {
                        cell.imageView?.image = UIImage(data: data!)
                        self.cache.setObject((cell.imageView?.image)!, forKey: NSString(string: imgUrl))
                        cell.setNeedsLayout()
                    }

                }).resume()
        }
        return cell
   }
let cache=NSCache()
重写func tableView(tableView:UITableView,cellForRowAt indexath:indexPath)->UITableViewCell{
let cell=tableView.dequeueReusableCell(标识符:idForCell,for:indexath)
让usr=userList[indexPath.row]
cell.textlab?.text=usr.name
cell.detailTextLabel?.text=usr.email
如果cell.imageView?.image!=nil{
返回单元
}
let key=NSString(字符串:usr.imgUrl!)
if cache.object(forKey:key)!=nil{
cell.imageView?.image=cache.object(forKey:key)!作为UIImage
返回单元
}
如果让imgUrl=usr.imgUrl{
让url=NSURL(字符串:imgUrl)
URLSession.shared.dataTask(其中:url为!url,completionHandler:{(数据,响应,错误))位于
如果错误!=零{
打印(呃!)
返回
}
DispatchQueue.main.async{
cell.imageView?.image=UIImage(数据:数据!)
self.cache.setObject((cell.imageView?.image)!,forKey:NSString(string:imgUrl))
cell.setNeedsLayout()单元格
}
})1.简历()
}
返回单元
}

您对NSCache的使用看起来很合理。您需要提供比“网络活动增加”更多的信息,以了解发生了什么。请注意,检查排队的单元格是否已经有映像的代码是错误的。回收单元中的现有图像几乎肯定是错误的图像。还要注意,您正在滥用
强制展开操作符。如果强制展开的任何选项为零,则代码将崩溃。你应该使用
guard
if let
,或者
??
。就缓存过程而言,我觉得一切都很好。我想看看:图像是否保存到缓存中?如果是,关键是什么?是否匹配?缓存获取一些元素,但键从不匹配:/