如何知道闭包是否归班级所有?

时间:2015-09-20 12:06:47

标签: swift closures

我很难弄清楚如何确保何时在封闭体中使用[弱自我] / [无主自我]。在下面显示的两个场景中,根据我的说法,它取决于B类是否拥有传递的闭包。

现在如果隐藏了B类的实现,我不确定如何决定使用[弱自我] / [无主自我]。

有人可以帮我理解你的决定吗?

/******** Scenario 1 **********/

class A {
    var b:B?
    let p = "Some Property of A"

    init() {
        print("Init of A")

        self.b = B(closure: { (number) -> Void in
            print(self.p)       // capturing self but still no need to write [weak/unowned self]
            print(number)
        })
    }

    deinit {
        print("Deinit of A")
    }
}

// Suppose this is a library class whose implementation is hidden
class B {
    init(closure:(Int->Void)) {
        print("Init of B")
        // ... do some work here
        closure(20)
    }
    deinit {
        print("Deinit of B")
    }
}

var a:A? = A()
a = nil

输出:

//    Init of A
//    Init of B
//    Some Property of A
//    20
//    Deinit of A
//    Deinit of B

现在是导致参考周期的第二种情况。

/******** Scenario 2 **********/

class A {
    var b:B?
    let p = "Some Property of A"
    init() {
        print("Init of A")

        self.b = B(closure: { (number) -> Void in
            print(self.p)       // capturing self but NEED to write [weak/unowned self]
            print(number)
        })
    }

    deinit {
        print("Deinit of A")
    }
}

// Suppose this is a library class whose implementation is hidden
class B {
    let closure:(Int->Void)

    init(closure:(Int->Void)) {
        print("Init of B")
        self.closure = closure     //class B owns the closure here
        f()
    }

    func f() {
        self.closure(20)
    }
    deinit {
        print("Deinit of B")
    }
}

var a:A? = A()
a = nil 

0 个答案:

没有答案