Hello! I have a question regarding memory manageme...
# kotlin-native
d
Hello! I have a question regarding memory management in kotlin/native and obj-c. How GC and ARC work together? Thank you
m
Quite simple i think: The GC increments the refcount by 1 while it own’s an object and decrements it by 1 when it considers the object not part of it’s graph anymore.
d
Are you sure that GC is implemented the same way as ARC in obj-c?
m
I do not pretend to understand fully how the GC works internally. I had to work on integrating KMP with a project that does not use ARC and that’s how I notice that when I receive an object that was created by KMP, it already has a refcount of one and as soon as the GC does it thing, the refcount decreases by 1. I do not see how it could work otherwise. So from ARC perspective, the GC is simply another object taking ownership by calling
retain
and relinquishing ownership by calling
release
like we did in the old days.
d
But what about code compiled from Kotlin side, that was received the obj-c object? How it will manage the ref count etc.?
m
when an object is received by swift or objective-c ARC takes care of the refcount like any other object it creates itself
d
Is there any ownership of the object in the Kotlin/native module? K/N Module received an object from iOS framework, how it’s memory would be managed? ARC works only on compile time, so there are no impact on K/N module
m
I would guess that the Kotlin/Native module calls
retain
on a object it receives thru the GC
d
@Marc Lefrancois,thank you for the feedback
m
Maybe someone from the GC team at Jetbrains can chip in some better explanation 🙂
d
I hope somebody from Kotlin team could explain. I saw this statement in the source code: “// Reference from an ObjC associated object back into a Kotlin object. // GC automatically tracks references with refcount > 0 as roots, and invalidates references with refcount = 0 when the Kotlin object is // collected. Use
create
and
dispose
to create and destroy the back reference.” Probably you are correct.
a
Essentially, that's how it works yes. Obj-C/Swift objects are retained by the Kotlin objects until the GC decides that the Kotlin object is no longer referenced. And in the other direction Kotlin objects are being strongly held by Obj-C/Swift objects when their RC is >0.