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

时间:2016-04-23 18:49:46

标签: ios swift caching

我有一个集合视图,其中包含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
}

1 个答案:

答案 0 :(得分:4)

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

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

HomepageCollectionViewController.imageCache.removeObjectForKey(image.imageUrl!)

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

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