Hey folks, I’ve noticed some odd behavior when pas...
# ios
s
Hey folks, I’ve noticed some odd behavior when passing references for Kotlin objects to ObjC objects. For example, I’m using the MapLibre pod, which has a
UIView
called
MLNMapView
. This view takes a delegate of the
MLNMapViewDelegate
protocol, which is notified on map movement. So in Kotlin, I implement the
MLNMapViewDelegateProtocol
interface and set
myMapView.delegate
to an instance of that implementation. And when the map is moved, I
println
the new position. What I’ve found is that after a few seconds, my instance stops getting notified of map movements. But if in Kotlin I maintain a reference to this delegate instance, the problem goes away; my delegate functions indefinitely. It’s not just the map view delegate; I’ve noticed the same thing passing a Kotlin object as a
target
to a
UIGestureRecognizer
. If I don’t hold a reference to my target in Kotlin land somewhere, the gesture recognizer stops working. Based on the above, I suspect the kotlin object is getting garbage collected when the only reference to it is in an objc object. Is this expected? Should I treat delegates and similar things as weak references only?
okay, answered my own question, partially: • MLNMapView’s delegate is marked as
weak
in the docs, I just never noticed (or knew that was an objc feature at all) • UIGestureRecognizer doesn’t say whether it’s weak or not in the docs but I guess I should assume it’s weak
a
You're right. Generally, all delegates/targets/target-action patterns in Obj-C are week-referenced. From another side, you have to keep in mind that all fields by default are strong in Swift/Obj-C. Hence, reference loops like
Kotlin Object 1 -> Swift/Obj-C Object -> Kotlin Object 2 -> Kotlin Object 1
will create memory leaks and cannot be cleared by GC.