块完成后仅返回 [英] After BLOCK Completed only Return

查看:121
本文介绍了块完成后仅返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是用于使以下代码按顺序工作的解决方案.

May I know is what are the solution to use in order to make the following code working in order.

- (CGFloat)getRowImageHeight
{
    CGFloat defaultHeight   = 300.f;
    __block CGFloat height  = defaultHeight;

    [self configureImageTVCell:self.itemImageTVCell
                         block:^(UIImage *image, BOOL succeeded) {
                             if( succeeded )
                                 height     = image.size.height;
                         }];

    return height;
}

我希望BLOCK在返回高度之前先完成,这是因为我想从BLOCK完成后获取最新高度.

I would expect the BLOCK to complete first before the return height, it is because I wanted to get the latest height from the completion of BLOCK.

我已经尝试过使用 dispatch_semaphore_t 来解决一些问题,但这会导致模拟器实际挂起的死锁.

I've tried a few solution by using dispatch_semaphore_t, but it causes deadlock where the simulator actually hang.

dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

[self configureImageTVCell:self.itemImageTVCell
                         block:^(UIImage *image, BOOL succeeded) {
                             if( succeeded )
                                 height     = image.size.height;

                             dispatch_semaphore_signal(semaphore);
                         }];

dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

为此已经不合时宜了,确实需要帮助.

Running out of idea for this already, need help indeed.

推荐答案

好的方法是这样的:

- (void)getRowImageHeightWithCompletionBlock:(void(^)(CGFloat height))completion {
    CGFloat defaultHeight = 300.f;
    [self configureImageTVCell:self.itemImageTVCell block:^(UIImage *image, BOOL succeeded) {
        if(succeeded && completion) {
            completion(image.size.height);
        }
    }];
}

这篇关于块完成后仅返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆