07-19-2023, 01:30 AM
I have a Swift class that needs to store a table of its own methods. Unfortunately this is causing a reference cycle, because its table retains references to `self` via the methods it stores.
Example leaky code below:
typealias Callback = ()->()
class CycleInducingClass : NSObject {
var myCallbacks = [Callback]()
override init() {
super.init()
myCallbacks.append(myInternalFunction)
}
func myInternalFunction() {
NSLog("lolol: %d", self.myCallbacks.count)
}
}
The only solution I've found so far is to instead do this:
myCallbacks.append({[unowned self] in self.myInternalFunction()})
That's pretty ugly, and prone to error. Any better ideas? Is there some trick for making the function references themselves be weak? i.e. to make the `myCallbacks` array of type `myCallbacks : [WeakCallback]()` or something? As far as I can tell I can't even build a convenience function `weaken` as syntactic sugar over the ugly closure wrapper above.
Example leaky code below:
typealias Callback = ()->()
class CycleInducingClass : NSObject {
var myCallbacks = [Callback]()
override init() {
super.init()
myCallbacks.append(myInternalFunction)
}
func myInternalFunction() {
NSLog("lolol: %d", self.myCallbacks.count)
}
}
The only solution I've found so far is to instead do this:
myCallbacks.append({[unowned self] in self.myInternalFunction()})
That's pretty ugly, and prone to error. Any better ideas? Is there some trick for making the function references themselves be weak? i.e. to make the `myCallbacks` array of type `myCallbacks : [WeakCallback]()` or something? As far as I can tell I can't even build a convenience function `weaken` as syntactic sugar over the ugly closure wrapper above.