gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:27:00 24 4
gpt4 key购买 nike

在我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com