0

我正在编写一个需要在缓存中存储一​​些图像的应用程序。我正在尝试用 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:对不起我的英语,我知道这很糟糕

4

2 回答 2

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;
}

您可能希望将图像的获取放在在另一个线程中运行的方法中并返回某种占位符图像。

于 2012-05-30T10:27:49.293 回答
1

除了@rckoenes 提供的答案之外,您无论如何都没有正确分配缓存实例;它应该是:

cache = [[NSCache alloc] init];

应该将哪个移到您的init方法中。

于 2012-05-30T10:30:07.643 回答