如何从方法的闭包中删除强引用循环?

时间:2016-10-06 14:44:38

标签: methods closures swift3 capture-list reference-cycle

这里我有一些关闭强参考周期的例子。 如果我为存储的属性分配一个闭包,我可以使用闭包捕获列表使捕获的引用无主/弱。 但是,如果我将一个方法分配给存储的属性闭包或将该方法分配给外部作用域中的闭包,我就不能使用捕获列表。

在最后两种情况下,我该怎么做才能删除参考周期?

创建和避免强引用循环的示例,其中捕获列表仅包含闭包

internal class ClosureClass {
    internal let p1: String
    internal lazy var p2: () -> String = {
        [unowned self] // if you comment this out there is a strong reference cycle
        () -> String in
        return self.p1
    }

    internal init() {
        self.p1 = "Default value of ClosureClass"
    }

    deinit {
        print("Object with property '\(self.p1)' is being deinitialized")
    }
}
print("Test 'Closure with strong reference to self':")
var cc: ClosureClass? = ClosureClass.init()
cc!.p2() // lazy need to call it once, else it will not be initiliazed
cc = nil

使用方法

的闭包创建强引用循环的示例
internal class MethodToClosureClass {

    internal let p1: String
    internal lazy var p2: () -> String = method(self) // Why not self.method ? Will create a strong reference cycle, but I can not set the reference to weak or unowned like in closures with the closure capture list

    internal init() {
        self.p1 = "Default value of MethodToClosureClass"
    }

    internal func method() -> String {
        //      [unowned self] in
        return self.p1
    }

    deinit {
        print("Object with property '\(self.p1)' is being deinitialized")
    }
}
print("Test 'Set closure with method intern':")
var m2cc: MethodToClosureClass? = MethodToClosureClass.init()
m2cc!.p2() // lazy need to call it once, else it will not be initiliazed
m2cc = nil

使用从extern

的方法设置闭包来创建强引用循环的示例
internal class MethodClass {
    internal let p1: String
    internal var p2: () -> String = {
        return ""
    }

    internal init() {
        self.p1 = "Default value of MethodClass"
    }

    internal func method() -> String {
        //      [unowned self] in
        return self.p1
    }

    deinit {
        print("Object with property '\(self.p1)' is being deinitialized")
    }
}
print("Test 'Set closure with method extern':")
var mc: MethodClass? = MethodClass.init()
var method: () -> String = mc!.method // will create a strong reference
mc!.p2 = method
mc = nil

输出

  

测试'关闭强烈引用自我':

     

具有属性的对象'ClosureClass的默认值'正在被取消初始化

     

使用方法实习'测试'设置闭包':

     

测试'使用方法extern设置闭包':

1 个答案:

答案 0 :(得分:3)

self.method只是用于创建闭包的语法糖(具有默认捕获模式,强大):{ () in self.method() }。如果你想使用一个明确的捕获列表,不要使用语法糖 - 明确地创建一个闭包(它是它所做的):

{ [unowned self] () in self.method() }