swift - 在嵌套函数中 self 捕获

标签 swift memory-management weak-references nested-function capture-list

对于闭包,我通常将 [weak self] 附加到我的捕获列表中,然后对 self 进行空检查:

func myInstanceMethod()
{
    let myClosure =
    {
       [weak self] (result : Bool) in
       if let this = self
       { 
           this.anotherInstanceMethod()
       }
    }   

    functionExpectingClosure(myClosure)
}

如果我使用嵌套函数代替闭包,我该如何对 self 执行 null 检查(或者检查是否必要......或者使用像这样的嵌套函数)即

func myInstanceMethod()
{
    func nestedFunction(result : Bool)
    {
        anotherInstanceMethod()
    }

    functionExpectingClosure(nestedFunction)
}

最佳答案

不幸的是,只有闭包有像[weak self]这样的“捕获列表”特性。对于嵌套函数,您必须使用普通的 weakunowned 变量。

func myInstanceMethod() {
    weak var _self = self
    func nestedFunction(result : Bool) {
        _self?.anotherInstanceMethod()
    }

    functionExpectingClosure(nestedFunction)
}

关于swift - 在嵌套函数中 self 捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26665076/

相关文章:

java - 为什么我的实例被垃圾收集

ios - 尝试构建存档 Xcode : clang: error: linker command failed with exit code 1 (use -v to see invocation) 时出错

ios - 从解析查询获取 tableView 中的值的延迟

java - 一个大数组会完全用Java存储在内存中吗?

c - 在 C 中组织数据的最快方法是什么?

ios - Swift 函数变量需要弱引用吗?

swift - UIButton 在 ContainerView 之外

ios - 快速格式化货币返回 nil

linux - 运行一个大小为 "Unlimited Stack"的应用会有什么影响?

ios - 为什么这个硬编码的字符串没有被释放,而 alloc/inited 的字符串呢?