2012-05-30 28 views
0

我在寫一個應用程序,需要在緩存中存儲一​​些圖像。我試圖用NSCache做到這一點,代碼似乎很好,但不要將圖像保存在緩存中。我有這樣的代碼:NSCache不起作用

緩存是全球性的,在.H聲明:NSCache *cache;

-(UIImage *)buscarEnCache:(UsersController *)auxiliarStruct{ 
    UIImage *image; 
    [[cache alloc] init]; 

    NSLog(@"cache: %i", [cache countLimit]); 
    if ([cache countLimit] > 0) { //if [cache countLimit]>0, it means that cache isn't empty and this is executed 
     if ([cache objectForKey:auxiliarStruct.thumb]){  
      image = [cache objectForKey:auxiliarStruct.thumb]; 
     }else{ //IF isnt't cached, is saved 
      NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb]; 
      NSURL *imageURL = [NSURL URLWithString:imageURLString]; 
      NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; 
      image = [UIImage imageWithData:imageData]; 
      [cache setObject:image forKey:auxiliarStruct.thumb]; 
     }   
    }else{ //This if is executed when cache is empty. IS ALWAYS EXECUTED BECAUSE FIRST IF DOESN'T WORKS CORRECTLY 
     NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb]; 
     NSURL *imageURL = [NSURL URLWithString:imageURLString]; 
     NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; 
     image = [UIImage imageWithData:imageData]; 
     [cache setObject:image forKey:auxiliarStruct.thumb]; 
    } 
    return image; 
} 

調用此功能在其他功能與此:

 UIImage *image = [self buscarEnCache:auxiliarStruct]; 

這工作,因爲顯示圖像在屏幕上,但不保存在緩存中,我認爲失敗的路線是:

[cache setObject:image forKey:auxiliarStruct.thumb]; //auxiliarStruct.thumb is the name of the image

有人知道爲什麼緩存不起作用?謝謝!!

PS:抱歉,我的英語水平,我知道是壞

回答

5

每次方法buscarEnCache:被稱爲新的高速緩存對象與行創建:

[[cache alloc] init]; 

因此舊的緩存剛剛泄露和不再可用。

cache = [[NSCache alloc] init];放在類的init方法中。


有沒有需要檢查的countLimit。

-(UIImage *)buscarEnCache:(UsersController *)auxiliarStruct{ 
    UIImage *image = [cache objectForKey:auxiliarStruct.thumb]; 

    if (!image) {  
     NSString *imageURLString = [NSString stringWithFormat:@"http://mydomain.com/%@",auxiliarStruct.thumb]; 
     NSURL *imageURL = [NSURL URLWithString:imageURLString]; 
     NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; 
     image = [UIImage imageWithData:imageData]; 
     [cache setObject:image forKey:auxiliarStruct.thumb]; 
    } 

    return image; 
} 

您可能希望將圖像的獲取放在另一個線程中運行的方法中,並返回某種佔位符圖像。

+0

我將該行移至viewDidLoad,但結果相同。 –

+0

對不起,我在我的答案中犯了錯誤,理論依然如此,只是你分配和初始化方式不對。 – rckoenes

+0

它的工作原理,謝謝! –

1

除了@rckoenes提供的答案外,您還沒有正確分配緩存實例;它應該是:

cache = [[NSCache alloc] init]; 

應將其移入您的init方法。

+0

我將該行移至viewDidLoad,但結果相同。 –

+0

爲什麼不能在快速緩存中工作? –