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

标签 swift swift3 escaping closures

在我的示例中,我在其他函数内创建实例。在函数结束时,我希望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/

相关文章:

xcode - 在多个项目上共享快速代码

ios - 快速将文本添加到图像中的一个点

swift - 比较两个 Int

xslt - 禁用输出转义 ="yes-no"不起作用并在 Sharepoint URL 中输出两次

javascript - 执行以下操作是否 100% 安全?

c# - Unescape转义字符串?

JSON Swift 解包 [""]

ios - 我们可以让 iOS 应用向后兼容吗

swift - Systemfont(旧金山)和 UltraLight

ios - Objectmapper字典到Json swift? swift 2 -> swift 3