2016-04-23 8 views
1

私はネットワークコールから取得する12のイメージを持つコレクションビューを持っています。私はそれらをキャッシュするためにNSCacheを使用します。そこから特定のイメージを削除する方法を知りたいですか?私は画像をどのようにキャッシュしたかを示すために以下のコードをいくつか提供しました。ありがとう!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 
} 
+0

@ozgurただ投稿しました! – SteveSmith

答えて

3

NSCacheアイテムを取り出す追加または削除のために同じAPIを共有するNSDictionaryのクラスのよりスマートなバージョンです。

したがって、あなたは辞書から行う場合と同じ方法を使用して、それから項目を削除することができます。

HomepageCollectionViewController.imageCache.removeObjectForKey(image.imageUrl!) 

あなたが表示ちょうど約あるキャッシュから画像を削除するようにコードを更新することができます。

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

助けてくれてありがとう! – SteveSmith

関連する問題