首先,这不是一个重复的问题。我已经阅读了很多关于 Stack Overflow 的问题,但它们并没有完全解决我的问题。
我正在从网络服务下载图像。由于没有人喜欢 UI 停滞不前,我使用线程单独下载图像。
NSURL *imageUrl = [NSURL URLWithString:storyImageURL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
thumbnailData = [NSData dataWithContentsOfURL:imageUrl];
dispatch_async(dispatch_get_main_queue(), ^{
thumbnail = [UIImage imageWithData:thumbnailData];
});
});
如果我完全按照上面的方式使用代码,UI 将不会停止,直到它从 Web 服务获取数据但图像没有被缓存。
如果我不使用线程,那么 UI 将停止,但图像会使用 NSCoding 方法(存档)进行缓存。
我的问题是:我该怎么做才能同时使用线程和缓存缩略图?请不要建议任何第三方库。
更新:一遍又一遍地查看代码后,我可能会想到两个问题:
1)看起来 NSKeyedArchiver 和 NSKeyedUnarchiver 在线程完成下载图像之前被调用,但这只是一个猜测。在单独的存储文件中,我使用 NSKeyedArchiver 和 NSKeyedUnarchiver:
- (RSSChannel *)fetchRSSFeedWithCompletion:(void (^)(RSSChannel *, NSError *))block
{
NSURL *url = [NSURL URLWithString:@"http://techcrunch.com/feed"];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
RSSChannel *channel = [[RSSChannel alloc] init];
TheConnection *connection = [[TheConnection alloc] initWithRequest:req];
//[connection setCompletionBlock:block];
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
cachePath = [cachePath stringByAppendingPathComponent:@"HAHAHA.archive"];
RSSChannel *cachedChannel = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
if (!cachedChannel)
cachedChannel = [[RSSChannel alloc] init];
RSSChannel *channelCopy = [cachedChannel copy];
[connection setCompletionBlock:^(RSSChannel *obj, NSError *err) {
if (!err) {
[channelCopy addItemsFromChannel:obj];
[NSKeyedArchiver archiveRootObject:channelCopy toFile:cachePath];
}
block(channelCopy, err);
}];
[connection setXmlRootObject:channel];
[connection start];
return cachedChannel;
}
2)我能想到的第二个问题是他的 UI 在尝试将缩略图解码出缓存后没有刷新。