【问题标题】:Does a nested closure cause retain cycle?嵌套闭包会导致保留周期吗?
【发布时间】:2016-03-28 20:48:33
【问题描述】:

当只有外部闭包是来自self 的引用时,我是否需要在内部闭包中使用weak self?外闭包是否捕获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()
    }
}

【问题讨论】:

  • 是的,您需要weak self。我想你可能真的需要它在外部封闭。

标签: ios swift


【解决方案1】:

问题不在于闭包是嵌套的。问题是 self 对闭包有一个强引用,所以如果闭包对 self 有一个强引用,就会得到一个引用循环。

但是,代码仍然有一个引用循环。内部闭包不会从调用代码中获取 self ,而是从外部闭包中获取。所以外闭包对 self 有一个不可见的强引用。外部封闭需要“弱自我”。

【讨论】:

  • 根据this article 通常你不必担心使用weak 引用来避免dispatch_async() 的保留循环,因为该块不属于self
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 2015-03-21
相关资源
最近更新 更多