如何从 NSCache 中删除特定图像?

Ste*_*ith 2 caching ios swift

我有一个集合视图,其中包含我从网络调用中检索的 12 个图像。我使用 NSCache 来缓存它们。我想知道如何从那里删除特定图像?我在下面提供了一些代码来展示我如何缓存图像。谢谢!

  override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageReuseCell", forIndexPath: indexPath) as! ImageCollectionViewCell

    let image = hingeImagesArray[indexPath.row]


    //Start animating activity indicator
    cell.actitivityIndicator.startAnimating()

    if let imageURL = image.imageUrl {

        if let url = NSURL(string: imageURL) {

            //Check for cached images and if found set them to cells - works if images go off screen
            if let myImage = HomepageCollectionViewController.imageCache.objectForKey(image.imageUrl!) as? UIImage {

                cell.collectionViewImage.image = myImage


            }else {


            // Request images asynchronously so the collection view does not slow down/lag
            let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in


                    // Check if there is data returned
                    guard let data = data else {

                   print("There is no data")
                        return
                    }

                    if let hingeImage = UIImage(data: data){

                      //Cache images/set key for it
                      HomepageCollectionViewController.imageCache.setObject(hingeImage, forKey: image.imageUrl!)

                       // Dispatch to the main queue
                       dispatch_async(dispatch_get_main_queue(), { () -> Void in

                        //Hide activity indicator and stop animating
                        cell.actitivityIndicator.hidden = true
                        cell.actitivityIndicator.stopAnimating()

                        //Set images to collection view
                        cell.collectionViewImage.image = hingeImage


                         })

                    }

                })

            task.resume()

           }
        }

    }

    return cell
}
Run Code Online (Sandbox Code Playgroud)

ozg*_*gur 5

NSCache 是 NSDictionary 类的更智能版本,它共享用于检索、添加或删除项目的相同 API。

因此,您可以使用与从字典中相同的方法从中删除项目:

HomepageCollectionViewController.imageCache.removeObjectForKey(image.imageUrl!)
Run Code Online (Sandbox Code Playgroud)

您可以更新代码以从缓存中删除即将显示的图像:

if let myImage = HomepageCollectionViewController.imageCache.removeObjectForKey(image.imageUrl!) as? UIImage {
  // myImage was removed from cache.
  cell.collectionViewImage.image = myImage
  ...
Run Code Online (Sandbox Code Playgroud)