0

因此,我正在尝试将最近访问的图像保存在缓存中,并在重新请求它们时将它们加载回来。问题是从缓存请求的图像没有显示,但从网络请求的图像却显示了。然而,经过大量的摆弄后,我发现将缓存数据功能与主队列上的请求结合起来似乎可以解决问题。谁能向我解释它为什么有效?我以为我会默认在主队列上?

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];      
}

}
4

0 回答 0