在我的 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 返回错误的缓存数据?