Wondering if anyone could help me with memory issu...
# kotlin-native
a
Wondering if anyone could help me with memory issues on iOS? I'm trying to figure out how to keep a weak reference to a UIViewController within a Kotlin class instance, without preventing the ViewController from deiniting. This is what I'm currently trying on the Kotlin side:
Copy code
class KotlinWeakViewController(private val weak: WeakReference<UIViewController>) {
    constructor(viewController: UIViewController) : this(WeakReference(viewController))

    val viewController get() = weak.get()
}
And I have this in my Swift VC:``` private var weakVc: KotlinWeakViewController? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) //weakVc = KotlinWeakViewController(viewController: self) weakVc = KotlinWeakViewController(weak: KotlinWeakReference(referred: self)) weakVc = nil } deinit { print("ViewController deinit") } ``` Unfortunately the ViewController never seems to deinit if I instantiate the
KotlinWeakViewController
, regardless of whether I create the
WeakReference
on the Kotlin side or on the Swift side, and regardless of whether I keep the reference to the
KotlinWeakViewController
around in an instance variable or nil it immediately.
k
If you’ve got a sample to poke at, it would be easier to discuss.
a
I unfortunately don't have access to a Mac right now to set up a sample project, but there wasn't really much code other than what I posted. I just dismissed the VC and noted that if I hadn't instantiated the Kotlin KotlinWeakViewController the deinit block was called immediately, but if I had instantiated the Kotlin object it didn't. I'm really not familiar with the KN memory model. Perhaps the deinit block would be called eventually after a GC pass or something, though it never happened in the time I tested it? If so, is it possible to somehow trigger a GC or otherwise verify that I won't be leaking this ViewController?
a
@kpgalligan Yes, worked perfectly, thank you!
Though it feels a little sketchy relying on an internal GC mechanism, so I also created an intermediate class on the Swift side that holds a weak reference to the viewcontroller and delegates the specific calls I need to this VC and handles the case where it has been unloaded. Then I pass this intermediate object to the Kotlin side instead. Anyway, thanks, now I know to be careful with passing objects to the Kotlin side that might hold refernces that maintain a lot of memory.
k
This has come up in other contexts. Prior to 1.3.40, when object refs got to zero they’d be cleaned up immediately. Now there’s an allocation cache and a GC threshold before objects are cleaned up, which is OK except in interop cases where deinit is expected immediately
👍 1