简体   繁体   English

我们是否需要在Objective-C中使用弱自我?

[英]Do we need to use weak self in blocks in Objective-C?

I noticed Apple's documentation saying we need to avoid strong reference cycles when capturing self. 我注意到Apple的文档说我们需要在捕获self时避免强大的引用周期。

The block in the example is a property of self. 示例中的块是self的属性。

But what if I put a block as a local variable in a dispatch_async statement? 但是如果我在dispatch_async语句中将块作为局部变量放置怎么办?

In this case, it will not create a retain cycle even if I directly call a method of self, right? 在这种情况下,即使我直接调用自我方法,它也不会创建保留周期,对吧?

Is the following code generating weakSelf required in this article ? 以下代码是否会在本文中生成weakSelf?

// your code
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_main_queue(), ^{
    __strong typeof(weakSelf) strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf doThis];
        [strongSelf doThat];
        [Manager.sharedInstance updateSuccessCount];
    }
});

// more code

In the example given, using dispatch_async , there would be no retain cycle, so it would be safe to capture self strongly here. 在给出的示例中,使用dispatch_async ,将没有保留周期,因此在此强烈捕获self是安全的。 The only difference would be that if self were released by everything else between when this dispatch_async was called and when the block actually ran, it would slightly delay the actual deallocation of self for that brief time, and could affect which thread the deallocation actually occurs on as well. 唯一的区别是,如果在调用dispatch_async和块实际运行之间的其他所有东西都释放了self ,那么它会稍微延迟self在这短暂时间内的实际释放,并且可能会影响释放实际发生在哪个线程上同样。 But in general there's no harm in doing it either way when using dispatch_async . 但是一般来说,使用dispatch_async时,无论采用哪种方式都没有坏处。

One case where you may want to do it the way your example is written above is if the code run in the block is somewhat expensive and would only want to be done if absolutely necessary, and that it's unnecessary if self had already been released by everything else. 你可能想要按照上面的例子的方式进行的一种情况是,如果在块中运行的代码有点昂贵,并且只想在绝对必要的情况下完成,并且如果self已经被所有东西释放则不必要其他。

Another case may be if self uses a large amount of memory and gets deallocated normally right before something else starts consuming a lot of memory. 另一种情况可能是,如果self使用大量内存并且在其他东西开始消耗大量内存之前正常解除分配。 In that case you may not want those two instances to be allocated at the same time. 在这种情况下,您可能不希望同时分配这两个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM