我正在编写一个需要在缓存中存储一些图像的应用。我正在尝试使用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:对不起我的英语,我知道不好
答案 0 :(得分: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;
}
您可能希望将图像的提取放在另一个线程中运行的方法中,并返回某种占位符图像。
答案 1 :(得分:1)
除了@rckoenes提供的答案之外,你还没有正确分配缓存实例;它应该是:
cache = [[NSCache alloc] init];
应将哪些内容移入init
方法。