0

我正在使用此块在 iOS 5 应用程序中同步图像下载。逻辑很简单,如果图像在缓存中使用它,如果不下载它,我想 NSURLRequestReturnCacheDataElseLoad 正是这种行为。

    [factory.downloadImagesQueue addOperationWithBlock:^(){
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",IP2BaseImgURL,imgName]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url
                         cachePolicy:NSURLRequestReturnCacheDataElseLoad
                     timeoutInterval:15.0];

        NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
        if (cachedResponse!=nil) {
            NSLog(@"%@ found in cache",imgName);
            [delegate imageDidFinishDownload:[UIImage imageWithData:[cachedResponse data]] atIndexPath:indexPath];
        } else {
            NSError *error;
            NSURLResponse *response;
            NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if (data == nil) {
                FULL_ERROR_LOG(error)
            } else {
                NSLog(@"%@ downloaded",imgName);
                if (![response.MIMEType isEqualToString:@"image/png"] && ![response.MIMEType isEqualToString:@"image/jpeg"]) {
                    NSLog(@"Found wrong mime type: %@",response.MIMEType);
                    [delegate imageDidEncounterErrorWhileDownload:imgName atIndexPath:indexPath];
                } else {
                    NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
                    [[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:(NSURLRequest *)request];
                    [delegate imageDidFinishDownload:[UIImage imageWithData:data] atIndexPath:indexPath];
                }
            }
        }

    }];

我用三张图片做了一个测试。当我第一次下载它们时,我可以看到消息'downloaded MyimgName1.jpg''downloaded MyimgName2.jpg''downloaded MyimgName3.jpg',通过打开Cache.db,我可以看到我所有的图像都正确存储在其中.

但是,当我尝试再次下载时,只有第一个下载的图像显示消息“MyimgName1.jpg 在缓存中找到”,这意味着对于所有其他 2 和 3 请求,cachedResponse 为 nil:

    NSCachedURLResponse* cachedResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request];
    if (cachedResponse!=nil) { // <-- nil
    }

我在 NSCache 的设置或创建中遗漏了什么吗?

4

1 回答 1

0

该行:

[[NSURLCache sharedURLCache] storeCachedResponse:cachedResponse forRequest:(NSURLRequest *)request];

当 'cachedResponse' 的值为 nil 时,将始终存储 nil,因为它在 if 内。我想知道你是如何缓存任何东西的。

无论如何,您应该先分配一个新的 NSCachedURLResponse 实例,然后再将其插入缓存。附带说明一下,尝试更改缓存的容量,这可能是问题所在。您可以使用 setMemoryCapacity 更改它:

于 2012-11-10T11:47:11.873 回答