我正在写一个应用程序,需要在缓存中存储一些图像。我正在尝试用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
有人知道为什么缓存不工作了吗??谢谢!!
附言:很抱歉我的英语,我知道这很糟糕。
发布于 2012-05-30 18:27:49
每次调用方法buscarEnCache:时,都会使用下面的代码行创建一个新的缓存对象:
[[cache alloc] init];因此,旧的缓存刚刚泄漏,不再可用。
将cache = [[NSCache alloc] 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;
}您可能希望将图像的获取放在另一个线程中运行的方法中,并返回某种占位符图像。
发布于 2012-05-30 18:30:08
正如@rckoenes提供的答案一样,无论如何您都没有正确地分配缓存实例;它应该是:
cache = [[NSCache alloc] init];它应该移到您的init方法中。
https://stackoverflow.com/questions/10814182
复制相似问题