ディスクに保存されている同じリソースに対して複数の読み取り操作を実行しています。
場合によっては、読み取り操作自体が、同じリソースに対する要求間の時間よりも長くかかることがあります。そのような場合、読み取り操作をディスクからの 1 つの読み取り要求にまとめてから、同じ結果をさまざまな要求元に返すことが理にかなっています。
最初に、最初のフェッチ リソース リクエストの結果をキャッシュしようとしましたが、リソースの読み取りに時間がかかりすぎて、新しいリクエストが入ってきたため、これは機能しませんでした。つまり、リソースもフェッチしようとすることになります。
すでに進行中のリクエストに追加のリクエストを「追加」することはできますか?
私が今持っているコードは、この基本構造に従っています (これでは十分ではありません)。
-(void)fileForKey:(NSString *)key completion:(void(^)(NSData *data) {
NSData *data = [self.cache threadSafeObjectForKey:key];
if (data) {
// resource is cached - so return it - no need to read from the disk
completion(data);
return;
}
// need to read the resource from disk
dispatch_async(self.resourceFetchQueue, ^{
// this could happen multiple times for the same key - because it could take a long time to fetch the resource - all the completion handlers should wait for the resource that is fetched the first time
NSData *fetchedData = [self fetchResourceForKey:key];
[self.cache threadSafeSetObject:fetchedData forKey:key];
dispatch_async(self.completionQueue, ^{
completion(fetchedData);
return;
});
});
}