图像不会从iOS缓存加载

时间:2012-06-14 12:47:16

标签: ios caching asynchronous nsdata grand-central-dispatch

因此,我尝试将最近访问的图像保存在缓存中,并在重新请求时将其加载回来。问题是从缓存中请求的图像没有显示,但是从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);
}

这是scrollview设置方法

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

}

0 个答案:

没有答案