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.
If the method list is independent of the particular instance then you can make it a type property and avoid the reference cycle:
The array elements are “curried functions” of the type
compare Instance Methods are “Curried” Functions in Swift.
Try this way,