ios - NSURLConnection 返回错误的缓存数据

标签 ios objective-c nsurlconnection

在我的 AppDelegate 方法中我创建缓存

NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:(10 * 1024 * 1024) diskCapacity:(100 * 1024 * 1024) diskPath:nil];
[NSURLCache setSharedURLCache:URLCache];

我有下一个 NSURLConnection 类

@implementation ImageDownloader {
    NSURLConnection *serverConnection;
    NSMutableData *imageData;
}

- (void)startDownloading
{
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.link] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10];
    imageData = [NSMutableData new];
    serverConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [serverConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [serverConnection start];
}

- (void)cancelDownloading
{
    [serverConnection cancel];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [imageData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    UIImage *image = [[UIImage alloc] initWithData:imageData];
    [self sendDelegateImage:image];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self sendDelegateImage:nil];
}

- (void)sendDelegateImage:(UIImage *)image
{
    [self.delegate imageDownloader:self didLoadAtIndexPath:self.indexPath image:image];
}

@end

我在 tableView 单元格出现时使用它。第一次加载一切都很好,第一次使用缓存一切都很好,但是当我第三次加载我的 tableView 时,缓存数据返回非常小,而且我没有图像。为什么 NSURLConnection 返回错误的缓存数据?

最佳答案

您可以尝试实现 connection:didReceiveResponse:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
    {
        self.dataReceived = [[NSMutableData alloc] init];
    }

来自文档:

In rare cases, for example in the case of an HTTP load where the content type of the load data is multipart/x-mixed-replace, the delegate will receive more than one connection:didReceiveResponse: message. In the event this occurs, delegates should discard all data previously delivered by connection:didReceiveData:, and should be prepared to handle the, potentially different, MIME type reported by the newly reported URL response.

编辑: 另外,刚刚注意到您正在使用 [NSMutableData new] 来初始化您的数据;你应该使用 [NSMutableData alloc] init]

关于ios - NSURLConnection 返回错误的缓存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640650/

相关文章:

ios - 如何使用静态变量在 objective-c 中保存字符串?

iphone - 如何获取 CGPath 的 CGPoint

objective-c - 为什么要在这个语句中释放NSURLConnection实例呢?

ios - 如何检查 key 对中的 key 是否可用?

ios - 发布请求后发回回复

iphone - 将项目从 ARC 转换为 MRC

objective-c - 从 Apple TV TVML TVJS JavaScript 应用调用 Swift 代码

ios - 设置值 : @"application/json" forHTTPHeaderField: @"Content­-Type" Not Working

ios - POST header 和正文之间的随机延迟

c# - MonoTouch 中的 UISaveVideoAtPathToSavedPhotosAlbum 在哪里?