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.
functionsvariable as optional, and simply set it to nil after the execution since you want it to be deallocated after.