【问题标题】:Function that takes block as an argument doesnt always return将块作为参数的函数并不总是返回
【发布时间】:2012-10-26 13:42:02
【问题描述】:

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

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

         }];

【问题讨论】:

  • 块被调用了?

标签: iphone ios objective-c-blocks


【解决方案1】:

将缓存中的图像更改为如下所示:

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

用户不应该关心图像是否在缓存中,并且在任何情况下您的块都应该被称为异步。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多