0

我写了一个从网上下载图像的函数。它以块作为参数。一切正常,直到我添加了一些内存缓存。如果图像已经在缓存中,则函数不会返回(但块不是零)。

- (void) downloadImageFromURL:(NSURL *) url completionBlock:(void (^)(UIImage *image, NSError *error)) block {

dataHandler = [DataHandler sharedInstance];

UIImage *img=[dataHandler.avatarImages objectForKey:[url absoluteString]];
//image is in cache
if (img) {
    block(img, nil);
}
//not in cache, download it (works ok)
else {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul), ^{
        NSData *imageData = [NSData dataWithContentsOfURL:url];
        UIImage *picture=[UIImage imageWithData:imageData];
        if(picture) {
            //save to cache
            [dataHandler.avatarImages setObject:picture forKey:[url absoluteString]];
            block(picture, nil);
        }
        else {
            NSError *error = [NSError errorWithDomain:@"image_download_error" code:1
                                             userInfo:[NSDictionary dictionaryWithObject:@"Can't fetch data" forKey:NSLocalizedDescriptionKey]];
            block(nil, error);
        }

    });
}

该块的名称如下:

        ImageDownloader *idl=[[ImageDownloader alloc] init];

        NSURL *imageUrl=[NSURL URLWithString:ta.avatarUrl];
        [idl downloadImageFromURL:imageUrl completionBlock:^(UIImage *image, NSError *error)
         {
             if(!error) {
                 dispatch_async(dispatch_get_main_queue(), ^(void) {
                     logo.image=image;
                 });
             } else {
                 NSLog(@"error %@", error);
             }

         }];
4

1 回答 1

0

当缓存中的图像看起来像这样时,更改您对块的调用:

if (img) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        block(img, nil);
    });
}

用户不应该关心图像是否在缓存中,并且无论如何您的块应该被称为异步。

于 2012-10-26T13:47:49.963 回答