gpt4 book ai didi

swift - 转义闭包是否捕获强链接?

转载 作者:行者123 更新时间:2023-11-30 11:43:03 25 4
gpt4 key购买 nike

在我的示例中,我在其他函数内创建实例。在函数结束时,我希望instance2应该是nil,并且completionHandlers数组不应该有到SomeClass2的强链接,但是completionHandlers仍然有链接。

这看起来像 @escaping 闭包在 self 内部创建了强链接。

var completionHandlers: [() -> Void] = []

func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) {
completionHandlers.append(completionHandler)
}

class SomeClass {
var x = 10
func doSomething() {
let instance2 = SomeClass2()
instance2.doSomething2()
}
}

class SomeClass2 {
var x = 11
func doSomething2() {
someFunctionWithEscapingClosure {
// still exist
self.x = 77
}
}
}

let instance = SomeClass()
instance.doSomething()

completionHandlers.first!()

最佳答案

来自documentation :

If you assign a closure to a property of a class instance, and the closure captures that instance by referring to the instance or its members, you will create a strong reference cycle between the closure and the instance. Swift uses capture lists to break these strong reference cycles. For more information, see Strong Reference Cycles for Closures.

这里没有强引用循环,但提到闭包捕获了实例,这就是您的情况发生的情况。为了防止您可以显式地弱捕获它:

func doSomething2() {
someFunctionWithEscapingClosure { [weak self] in
self?.x = 77
}
}

关于swift - 转义闭包是否捕获强链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49125961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com