简体   繁体   English

在Swift关闭的闭包内使用无主

[英]Use of unowned inside the closure of the closure for Swift

I have a closure inside a closure, and the second closure use self, so both should have unowned self or just the second closure should have it? 我在一个闭包里面有一个闭包,第二个闭包使用self,所以两个都应该有无主的自我,或者只是第二个闭包应该有它?

dispatch_async(backgroundQueue) { [unowned self] () -> Void in
    dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
        self.doSomething()
    })
}

This is the retain graph without unowned , it doesn't have any cycles so you don't need unowned to break anything. 这是没有 unowned的保留图,它没有任何周期,所以你不需要unowned来破坏任何东西。

a -> b means a retain b a -> b表示保留b

backgroundQueue -> outerBlock -> self
                       |          ^
                       V          |
      mainQueue -> innerBlock -----

A cycle is formed only when self retain any of the blocks. 仅当self保留任何块时才形成循环。

Also note even backgroundQueue does retain outerBlock , the block will be released after executed, so in case self retain backgroundQueue , the retain cycle will not hold on. 另请注意,即使backgroundQueue确实保留了outerBlock ,该块也会在执行后释放,因此如果自我保留backgroundQueue ,保留周期将不会保持。


This is the retain graph with unowned (your code) 这是在保持unowned (代码)

a -x- b means a use b without retain it (unowned) a -x- b表示使用b而不保留它(无主)

  backgroundQueue -> outerBlock -x- self
                           |          |
                           V          x
          mainQueue -> innerBlock -----

you can see self is not retained by anything, which means when innerBlock is executed, self may be deallocated and cause your app crash. 你可以看到self 没有被任何东西保留,这意味着当执行innerBlock时,self可能会被释放并导致你的应用程序崩溃。

both should have unowned self or just the second closure should have it? 两者都应该拥有无主的自我,或者只是第二封应该拥有它?

None of the above. 以上都不是。 If you are just doing dispatch_async , the [unowned self] is a mistake. 如果您只是在执行dispatch_async ,那么[unowned self]是一个错误。 Delete it in both places. 在两个地方删除它。 Neither needs it. 都不需要它。

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

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