Hello, I have a question. Are there any memory lea...
# kotlin-native
a
Hello, I have a question. Are there any memory leaks in the following code? This view controller is created and used from Swift.
Copy code
fun myViewController(): UIViewController = MyViewControllerImpl()

private class MyViewControllerImpl : UIViewController(nibName = null, bundle = null) {
    private val button = UIButton()
    
    override fun viewDidLoad() {
        super.viewDidLoad()

        button.addTarget(target = this, action = sel_registerName("onClick"), forControlEvents = UIControlEventTouchUpInside)
        view.addSubview(button)
    }
    
    @ObjCAction
    private fun onClick() {
    }
}
s
No. Addtarget doesn't retain the object being sent to it. The only thing I would critique is that you're creating a view at construction time (button). Another more proper way of doing that is to override loadView. View controllers have a life cycle that doesn't always involve having a view created. On modern devices it isn't all that necessary to worry about, maybe on older ones running newer iOS versions but probably not.
a
Alright. What if
addTarget
would retain the reference. In this case would it be a memory leak?
s
If it did yes. You would have VC -> button and button -> VC. Although K/N does do some garbage collection so it may be smart enough to break the retain cycle. In straight Swift or objc it would definitely be a leak. You're more likely to find leaks using blocks and passing them off to other objects that keep the block around for a while.
a
This is the question. In Swift we have
deinit
and
weak var
. In Kotlin we don't have any. How to deal with cyclic references in such cases (when the class is created and used from Swift)?
a
That's makes sense, thanks!