【问题标题】:Is self captured within a nested function在嵌套函数中自我捕获
【发布时间】:2014-12-27 04:58:15
【问题描述】:

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

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

    functionExpectingClosure(myClosure)
}

如果我使用嵌套函数代替闭包,我如何对self 执行空检查(或者检查是否必要......或者使用这样的嵌套函数甚至是一种好习惯) 即

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

    functionExpectingClosure(nestedFunction)
}

【问题讨论】:

  • 从 rintaro 的答案中学习我写了一个更强大的答案here

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


【解决方案1】:

似乎不再是这种情况了。这在 swift 4.1 中有效:

class Foo {
    var increment = 0
    func bar() {
        func method1() {
            DispatchQueue.main.async(execute: {
                method2()
            })
        }

        func method2() {
            otherMethod()
            increment += 1
        }
        method1()
    }

    func otherMethod() {

    }
}

问题依然存在:self 是如何被捕获的?

【讨论】:

  • 如果“有效”是指self 未被强烈捕获,那么我不能批准。在我的情况下,我有一个闭包,我在这个闭包中调用了一个嵌套的func,并且该类不会被释放,即deinit 没有被调用。至少这是我的研究/调试向我展示的。
  • 这里会被强烈捕获
【解决方案2】:

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

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

    functionExpectingClosure(nestedFunction)
}

【讨论】:

  • 官方文档中有这个吗?
  • 看来这是真的。我做了一个测试,闭包中的弱点没有传递到嵌套函数中的 self 中。干净的代码就这么多。
  • 现在好像不是这样了。
猜你喜欢
  • 1970-01-01
  • 2022-01-14
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多