简体   繁体   中英

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 ? Does the outer closure capture self even when it's only used in the inner closure?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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