4

我有一个从块中检索的值,我想在下面的方法中返回该值。由于该块似乎是异步的,我该如何实现呢?

-(UIImage*) imageAtIndex:(NSUInteger)index
{
    UIImage *image;
    [self.album enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:0 usingBlock: ^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
            //set image in here
     }];

    return image;
}
4

2 回答 2

2

如果您的块是异步的,则您无法在 return is 之前设置返回值,因为程序可能在方法结束之前还没有完成异步任务。一些更好的解决方案是:

  1. 如果您愿意,请找到一个可以完成相同工作的同步方法。
    现在这可能不是最佳选择,因为您的 UI 会在块运行时锁定。

  2. 找到值时调用选择器,并使方法本身无效。

或许,尝试这样的事情:

-(void) findImageAtIndex:(NSUInteger)index target:(id)target foundSelector:(SEL)foundSEL
{
    __block UIImage *image;
    [self.album enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:0 usingBlock: ^(ALAsset *result, NSUInteger index, BOOL *stop)
    {
        //set image in here
        if ([target respondsToSelector:foundSEL]) { //If the object we were given can call the given selector, call it here
            [target performSelector:foundSEL withObject:image];
            return;
        }
    }];
    //Don't return a value
}

然后你可以这样称呼它:

    ...
    //Move all your post-finding code to bar:
    [self findImageAtIndex:foo target:self foundSelector:@selector(bar:)];
}

- (void)bar:(UIImage *)foundImage {
     //Continue where you left off earlier
     ...
}
于 2012-12-07T07:28:30.537 回答
2

我以前也是这样干的,看看。

-(void) imageAtIndex:(NSUInteger)index //since block is async you may not be able to return the image from this method
{

    UIImage *image;
    [self.album enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:0 usingBlock: ^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
         //set image in here
          dispatch_async(dispatch_get_main_queue(), ^{ //if UI operations are done using this image, it is better to be in the main queue, or else you may not need the main queue.
             [self passImage:image]; //do the rest of the things in `passImage:` method
          });
     }];
}
于 2012-12-07T07:18:05.983 回答