NSURLConnection返回错误的cacheData

时间:2013-09-05 15:42:32

标签: 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返回错误的缓存数据?

1 个答案:

答案 0 :(得分:2)

您可以尝试实施connection:didReceiveResponse:

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

来自文档:

  

在极少数情况下,例如在HTTP加载的情况下   加载数据的内容类型是multipart / x-mixed-replace ,.   delegate将收到多个连接:didReceiveResponse:   信息。如果发生这种情况,代表应丢弃所有数据   以前通过连接传递:didReceiveData:,应该是   准备处理由报告的可能不同的MIME类型   新报告的网址回复。

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