2013-08-26 81 views
1

我無法緩存和顯示緩存的圖像。 這是一個有很多圖像的集合視圖。iOS圖像沒有正確緩存

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 
    static NSString *identifier = @"Cell"; 
    CollectionViewCell *cell = (CollectionViewCell *)[self.collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; 

    UIImage *imageMP = [_imageCache objectForKey:[self getImage:indexPath.row]]; 

    NSLog(@"looking for \"%@\"",[self getImage:indexPath.row]); 

    if (imageMP) { 
     NSLog(@"found it!"); 
     cell.img_pic.image = imageMP; 

    }else{ 
     //display loading pic so long 
     cell.img_pic.image = [UIImage imageNamed:@"photo1.png"]; 

     [self.queue addOperationWithBlock:^{ 
      UIImage *image = [self getActualImage:indexPath.row]; 
      if (image) { 
       [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
        cell.img_pic.image = image; 
       }]; 
       [_imageCache setObject:image forKey:[self getImage:indexPath.row]]; 

       NSLog(@"saving as \"%@\"",[self getImage:indexPath.row]); 
      } 
     }]; 

    } 

它正確加載和顯示圖像,問題是保存到緩存,然後從緩存中顯示。

的的NSLog的控制檯輸出如下:

looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 
looking for "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 
saving as "/var/mobile/Applications/CAF51B4B-6FAF-4775-A201-EF670BB50462/Documents/7_MP.jpeg" 

它從來沒有正確顯示緩存的圖片,否則會打印出「找到了!」

我在做什麼錯?

回答

0

這解決了這一問題。

_imageCache = [[NSCache alloc] init]; 

我只是忘了分配和初始化NSCache。