关闭时封闭的无主自我

时间:2016-06-15 14:08:36

标签: swift closures retain-cycle weak

如果我在另一个闭包中有一个闭包就足以在外闭合中使用无主/弱一次以避免保留周期?

示例:

foo.aClosure({[unowned self] (allowed: Bool) in
            if allowed {
                self.doStuff()

                self.something.anotherClosure({ (s:String) -> (Void) in
                    self.doSomethingElse(s)
                })   
            }
        })

2 个答案:

答案 0 :(得分:1)

只有在外部闭包的捕获列表中声明弱或无主自我足以避免保留周期,如果你不在外部闭包内创建对self的强引用(例如通过做:guard let strongSelf = self别的{return})。

如果你确实在闭包中创建了一个强引用,你必须在内部闭包中添加一个捕获列表,以确保它捕获你对弱自我的强引用。

以下是一些例子:

dplyr

答案 1 :(得分:0)

是的,但是我会使用弱的无主,因为self.doStuff()如果你使用弱和它自己的话会抛出异常吗?.doStuff()不会抛出异常并且它只是赢了'执行。

您可以在操场上使用以下代码进行测试:

typealias Closure = () -> Void

class ClosureObject {
    var closure:Closure?
    func saveClosure(closure:Closure?) {
        self.closure = closure
    }
}

let mainClosureObject = ClosureObject()

class TestObject {
    let closureObject = ClosureObject()
    func log() {
        print("logged")
    }
    func run() {
        mainClosureObject.saveClosure() {[weak self] in
            self?.closureObject.saveClosure() {
                self?.log()
            }
        }
    }
}

var testObject:TestObject? = TestObject()
let closureObject = testObject?.closureObject
testObject?.run()
mainClosureObject.closure?()
closureObject?.closure?()
testObject = nil
closureObject?.closure?()
mainClosureObject.closure?()
closureObject?.closure?()

并将其与:

进行比较
typealias Closure = () -> Void

class ClosureObject {
    var closure:Closure?
    func saveClosure(closure:Closure?) {
        self.closure = closure
    }
}

let mainClosureObject = ClosureObject()

class TestObject {
    let closureObject = ClosureObject()
    func log() {
        print("logged")
    }
    func run() {
        mainClosureObject.saveClosure() {
            self.closureObject.saveClosure() {
                self.log()
            }
        }
    }
}

var testObject:TestObject? = TestObject()
let closureObject = testObject?.closureObject
testObject?.run()
mainClosureObject.closure?()
closureObject?.closure?()
testObject = nil
closureObject?.closure?()
mainClosureObject.closure?()
closureObject?.closure?()