そのため、最近アクセスした画像をキャッシュに保存し、再要求された場合にそれらをロードしようとしています。問題は、キャッシュから要求された画像は表示されませんでしたが、Web から要求された画像は表示されました。しかし、いろいろいじった後、キャッシュデータ関数をメインキューのリクエストで囲むと、問題が解決するように見えることがわかりました。なぜそれが機能するのか、誰かが私に説明できますか? デフォルトでメインキューにいると思っていましたか?
if([self.fileManager fileExistsAtPath:fileName]){
NSData *theData = [NSData dataWithContentsOfFile:fileName];
dispatch_async(dispatch_get_main_queue(), ^{ // Why does it work now?
[self setUpScrollViewWithImageData:theData];
});
}else{
dispatch_queue_t downloadQueue = dispatch_queue_create("flickr download", NULL);
dispatch_async(downloadQueue, ^{
NSData *imageData = [NSData dataWithContentsOfURL:image];
dispatch_async(dispatch_get_main_queue(), ^{
[self setUpScrollViewWithImageData:imageData];
[self.fileManager createFileAtPath:fileName contents:imageData attributes:nil];
[self checkCacheSize];
});
});
dispatch_release(downloadQueue);
}
スクロールビューの設定方法です
-(void)setUpScrollViewWithImageData:(NSData *)imageDataToSetup{
UIImageView *myImage = [[UIImageView alloc] initWithImage:[UIImage imageWithData:imageDataToSetup]];
self.thisImage = myImage;
self.myScrollView.delegate =self;
self.myScrollView.contentSize = self.thisImage.bounds.size;
self.navigationItem.rightBarButtonItem = nil;
[self.myScrollView addSubview:self.thisImage];
self.myScrollView.minimumZoomScale = 0.2;
self.myScrollView.maximumZoomScale = 5;
float w = self.view.bounds.size.width/self.thisImage.bounds.size.width;
float h = self.view.bounds.size.height/self.thisImage.bounds.size.height;
float zoomRatioMax = MAX(w , h );
float zoomRatioMin = MIN(w , h );
if(zoomRatioMax<1){
[self.myScrollView setZoomScale:zoomRatioMax];
}
if(zoomRatioMin>1){
[self.myScrollView setZoomScale:zoomRatioMin];
}
}