我在寫一個應用程序,需要在緩存中存儲一些圖像。我試圖用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:抱歉,我的英語水平,我知道是壞
我將該行移至viewDidLoad,但結果相同。 –
對不起,我在我的答案中犯了錯誤,理論依然如此,只是你分配和初始化方式不對。 – rckoenes
它的工作原理,謝謝! –