简体   繁体   English

嵌套闭包是否会导致保留周期?

[英]Does a nested closure cause retain cycle?

Do I need to use weak self in the inner closure when only the outer one is references from self ? 当只有外部引用来自self时,是否需要在内部闭包中使用weak self self Does the outer closure capture self even when it's only used in the inner closure? 即使仅在内部封盖中使用,外部封盖也会捕获self吗?

self.myClosure = {
    // First do something in the background without self...

    // Then do something in the main thread with self...
    dispatch_async(dispatch_get_main_queue()) { 

        [weak self] in // IS THIS REALLY NEEDED?

        self?.underlyingImage = img
        self?.imageLoadingComplete()
    }
}

The problem is not that the closure is nested. 问题不在于闭包是嵌套的。 The problem is that self has a strong reference to the closure, so if the closure has a strong reference to self, you get a reference cycle. 问题是self对闭包有很强的引用,因此,如果闭包对self有很强的引用,则会获得一个引用周期。

However, the code still has a reference cycle. 但是,该代码仍然具有参考周期。 The inner closure doesn't take self from the calling code, but from the outer closure. 内部闭包不是从调用代码中获取自身,而是从外部闭包中获取自身。 So the outer closure has an invisible strong reference to self. 因此,外部封闭对自身具有无形的强烈引用。 The "weak self in" is needed on the outer closure. 外盖上需要“弱自吸”。

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

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