ARC __bridge cast Block_copy& Block_release [英] ARC __bridge cast Block_copy & Block_release

查看:74
本文介绍了ARC __bridge cast Block_copy& Block_release的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于某种原因,我希望在运行循环的下一次迭代期间执行一个块,所以我想到了:

For some reason I want a block to execute during the next iteration of the run loop, so I came up with:

typedef void (^resizer_t)() ;

- (void) applyResizer: (resizer_t) resizer {
    resizer() ;
    Block_release(resizer) ;
}

- (void) usage {
    ...
    resizer_t resizer = ^() {
        // stuff
    } ;

    [self performSelectorOnMainThread:@selector(applyResizer:)
                           withObject:(__bridge id) Block_copy((__bridge void *) resizer)
                        waitUntilDone:NO] ;
}

  1. 具有讽刺意味的是我不得不抛弃* 阻止 _copy?
  2. 为什么编译器在窒息时对我的Block_release感到满意 在没有桥梁void * cast的Block_copy上?
  1. Isn't it ironic that I have to cast to void * the argument to Block_copy ?
  2. Why is the compiler happy with my Block_release when it chokes on Block_copy without the bridge void * cast?

代码似乎可以正常工作,我没有检测到泄漏或过早发布,但是我对语法有点困惑……

The code seems to work, I didn't detect a leak nor a premature release, but I'm a bit puzzled by the syntax ...

推荐答案

块被视为对象,因此ARC阻止您将它们强制转换为void *而不进行显式桥接强制转换.奇怪的是,您的编译器没有在Block_release上抱怨:它应该(在我的机器上,它应该).

Block are treated as objects so ARC prevent you from casting them to void * without explicit bridged cast. It strange that your compiler doesn't complain on Block_release: it should (on my machine, it does).

由于ARC将块视为对象,因此不再需要使用Block_copyBlock_release.要将块移动到堆上,请复制该块(使用-[NSObject copy]),然后让编译器管理其余部分.

Because ARC treats block as objects, you shouldn't need to use Block_copy nor Block_release anymore. Copy the block (with -[NSObject copy]) when you want it to move to the heap and let the compiler manage the remainder.

-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]保留接收方和参数对象,直到调用该方法为止.因此,您的块将在需要时保留和释放.您要做的就是通过将copy消息传递给方法之前,确保该块未存储在堆栈中.

-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:] retains the receiver and the parameter object until the method is invoked. So your block will be retained and released when required. All you have to do is ensure that the block isn't stored on the stack by sending the copy message before passing it to the method.

此外,还有一种更简单的方式来调度块的执行:它是libdispatch(又名GCD).

Moreover, there is a simpler way to dispatch the execution of a block: it's libdispatch (aka GCD).

dispatch_async(dispatch_get_main_queue(), resizer);

这篇关于ARC __bridge cast Block_copy& Block_release的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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