【问题标题】:Could someone clarify this block for me?有人可以为我澄清这个块吗?
【发布时间】:2013-05-15 02:14:09
【问题描述】:

我正在处理块内使用的对象不会释放的问题。

首先我有这个代码:

__block SOMABannerView* bannerView=_bannerView;
self.viewWillDissappearObserver = [center addObserverForName:UIViewWillDissappearNotification object:self.delegate.viewControllerForPresentingModalView queue:mainQueue usingBlock:
    ^(NSNotification *note) {
        [bannerView setAutoReloadEnabled:NO];
     }]; 

我使用 __block 是因为它不会复制和保留对象,但是当我使用 Instruments 分析这段代码时,我注意到 SOMABannerView 类中的对象没有被释放,所以我将其更改为:

self.viewWillDissappearObserver = [center addObserverForName:UIViewWillDissappearNotification object:self.delegate.viewControllerForPresentingModalView queue:mainQueue usingBlock:
    ^(NSNotification *note) {
        [_bannerView setAutoReloadEnabled:NO];
     }]; 

这也不起作用,所以我最终使用 NSNotificationCenter 的另一种方法来避免阻塞,但我仍然不明白为什么 __block 保留了对象,有人可以为我澄清一下吗?我对 __block 有错误的概念吗?

【问题讨论】:

    标签: ios objective-c memory-leaks objective-c-blocks


    【解决方案1】:

    它不会在非 ARC 环境中保留对象,但它在 ARC 环境中。对于 ARC,请使用 __weak 而不是 __block

    来源:http://clang.llvm.org/docs/AutomaticReferenceCounting.html#blocks

    【讨论】:

    • "对于 ARC,使用 __weak" 或 __unsafe_unretained,如果 __weak 不可用
    • @newacct 好点。我已经好几年没有为 iOS 4 开发了^^;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    • 1970-01-01
    • 2014-05-21
    • 2017-01-28
    • 2012-07-06
    相关资源
    最近更新 更多