Array of methods in swift without reference cycle

限于喜欢 提交于 2019-12-12 21:15:31

问题


My goal is to create a class which contains an array. The elements of the array will be the methods of the same class. like:

class MyClass {
    lazy var functions = [self.myFirstMethod, self.mySecondMethod]

    deinit {
        print("Deinit")
    }

    func myFirstMethod() {
        // Do Something
    }

    func mySecondMethod() {
        // Do Something
    }

    func executeAll() {
        for f in functions {
            f()
        }
    }
}

When I call the executeAll() it works fine and I achieve my expected result:

var myObject = MyClass()
myObject.executeAll()

The problem is, it create reference cycle. Instance of MyClass holds the array functions and functions array holds self. So If I write below code:

var myObject: MyClass? = MyClass()
myObject.executeAll()
myObject = nil

It will not call deinit method because of this strong reference cycle. How can I add method pointers to array as weak self? I don't want to use a local copy of functions in executeAll method.


回答1:


If the method list is independent of the particular instance then you can make it a type property and avoid the reference cycle:

class MyClass {
    static let functions = [myFirstMethod, mySecondMethod]

    func executeAll() {
        for f in MyClass.functions {
            f(self)()
        }
    }

   // ...
}

The array elements are “curried functions” of the type

(MyClass) -> () -> ()

compare Instance Methods are “Curried” Functions in Swift.




回答2:


Try this way,

class Unowned<T: AnyObject> {
    unowned let value: T
    init(_ value: T) {
        self.value = value
    }
}

var myObject: MyClass = MyClass()
var myUnowned = Unowned(myObject)
myUnowned.value.executeAll()


来源:https://stackoverflow.com/questions/55038194/array-of-methods-in-swift-without-reference-cycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!