iOS 集成

This page describes the new memory manager enabled by default since Kotlin 1.7.20. See our migration guide to move your projects from the legacy memory manager that will be removed in Kotlin 1.9.20.

iOS 集成 - 图1

Integration of Kotlin/Native garbage collector with Swift/Objective-C ARC is seamless and generally requires no additional work to be done. Learn more about Swift/Objective-C interoperability.

However, there are some specifics you should keep in mind:

Threads

Deinitializers

Deinitialization on the Swift/Objective-C objects and the objects they refer to is called on the main thread if these objects are passed to Kotlin on the main thread, for example:

  1. // Kotlin
  2. class KotlinExample {
  3. fun action(arg: Any) {
  4. println(arg)
  5. }
  6. }
  1. // Swift
  2. class SwiftExample {
  3. init() {
  4. print("init on \(Thread.current)")
  5. }
  6. deinit {
  7. print("deinit on \(Thread.current)")
  8. }
  9. }
  10. func test() {
  11. KotlinExample().action(arg: SwiftExample())
  12. }

The resulting output:

  1. init on <_NSMainThread: 0x600003bc0000>{number = 1, name = main}
  2. shared.SwiftExample
  3. deinit on <_NSMainThread: 0x600003bc0000>{number = 1, name = main}

Deinitialization on the Swift/Objective-C objects is called on a special GC thread if:

  • Swift/Objective-C objects are passed to Kotlin on a thread other than main.
  • The main dispatch queue isn’t processed.

If you want to call deinitialization on a special GC thread explicitly, set kotlin.native.binary.objcDisposeOnMain=false in your gradle.properties. This option enables deinitialization on a special GC thread, even if Swift/Objective-C objects were passed to Kotlin on the main thread.

Completion handlers

When calling Kotlin suspending functions from Swift, completion handlers might be called on threads other than the main one, for example:

  1. // Kotlin
  2. // coroutineScope, launch, and delay are from kotlinx.coroutines
  3. suspend fun asyncFunctionExample() = coroutineScope {
  4. launch {
  5. delay(1000L)
  6. println("World!")
  7. }
  8. println("Hello")
  9. }
  1. // Swift
  2. func test() {
  3. print("Running test on \(Thread.current)")
  4. PlatformKt.asyncFunctionExample(completionHandler: { _ in
  5. print("Running completion handler on \(Thread.current)")
  6. })
  7. }

The resulting output:

  1. Running test on <_NSMainThread: 0x600001b100c0>{number = 1, name = main}
  2. Hello
  3. World!
  4. Running completion handler on <NSThread: 0x600001b45bc0>{number = 7, name = (null)}

Calling Kotlin suspending functions

The Kotlin/Native memory manager has a restriction on calling Kotlin suspending functions from Swift and Objective-C from threads other than the main one.

This restriction was originally introduced in the legacy memory manager due to cases when the code dispatched a continuation to be resumed on the original thread. If this thread didn’t have a supported event loop, the task would never run, and the coroutine would never be resumed.

In certain cases, this restriction is not required anymore. You can lift it by adding the following option to your gradle.properties:

  1. kotlin.native.binary.objcExportSuspendFunctionLaunchThreadRestriction=none

Garbage collection and lifecycle

Object reclamation

An object is reclaimed only during the garbage collection. This applies to Swift/Objective-C objects that cross interop boundaries into Kotlin/Native, for example:

  1. // Kotlin
  2. class KotlinExample {
  3. fun action(arg: Any) {
  4. println(arg)
  5. }
  6. }
  1. // Swift
  2. class SwiftExample {
  3. deinit {
  4. print("SwiftExample deinit")
  5. }
  6. }
  7. func test() {
  8. swiftTest()
  9. kotlinTest()
  10. }
  11. func swiftTest() {
  12. print(SwiftExample())
  13. print("swiftTestFinished")
  14. }
  15. func kotlinTest() {
  16. KotlinExample().action(arg: SwiftExample())
  17. print("kotlinTest finished")
  18. }

The resulting output:

  1. shared.SwiftExample
  2. SwiftExample deinit
  3. swiftTestFinished
  4. shared.SwiftExample
  5. kotlinTest finished
  6. SwiftExample deinit

Objective-C objects lifecycle

The Objective-C objects might live longer than they should, which sometimes might cause performance issues. For example, when a long-running loop creates several temporary objects that cross the Swift/Objective-C interop boundary on each iteration.

In the GC logs, there’s a number of stable refs in the root set. If this number keeps growing, it may indicate that the Swift/Objective-C objects are not freed up when they should. In this case, try the autoreleasepool block around loop bodies that do interop calls:

  1. // Kotlin
  2. fun growingMemoryUsage() {
  3. repeat(Int.MAX_VALUE) {
  4. NSLog("$it\n")
  5. }
  6. }
  7. fun steadyMemoryUsage() {
  8. repeat(Int.MAX_VALUE) {
  9. autoreleasepool {
  10. NSLog("$it\n")
  11. }
  12. }
  13. }

Garbage collection of Swift and Kotlin objects’ chains

Consider the following example:

  1. // Kotlin
  2. interface Storage {
  3. fun store(arg: Any)
  4. }
  5. class KotlinStorage(var field: Any? = null) : Storage {
  6. override fun store(arg: Any) {
  7. field = arg
  8. }
  9. }
  10. class KotlinExample {
  11. fun action(firstSwiftStorage: Storage, secondSwiftStorage: Storage) {
  12. // Here, we create the following chain:
  13. // firstKotlinStorage -> firstSwiftStorage -> secondKotlinStorage -> secondSwiftStorage.
  14. val firstKotlinStorage = KotlinStorage()
  15. firstKotlinStorage.store(firstSwiftStorage)
  16. val secondKotlinStorage = KotlinStorage()
  17. firstSwiftStorage.store(secondKotlinStorage)
  18. secondKotlinStorage.store(secondSwiftStorage)
  19. }
  20. }
  1. // Swift
  2. class SwiftStorage : Storage {
  3. let name: String
  4. var field: Any? = nil
  5. init(_ name: String) {
  6. self.name = name
  7. }
  8. func store(arg: Any) {
  9. field = arg
  10. }
  11. deinit {
  12. print("deinit SwiftStorage \(name)")
  13. }
  14. }
  15. func test() {
  16. KotlinExample().action(
  17. firstSwiftStorage: SwiftStorage("first"),
  18. secondSwiftStorage: SwiftStorage("second")
  19. )
  20. }

It takes some time between “deinit SwiftStorage first” and “deinit SwiftStorage second” messages to appear in the log. The reason is that firstKotlinStorage and secondKotlinStorage are collected in different GC cycles. Here’s the sequence of events:

  1. KotlinExample.action finishes. firstKotlinStorage is considered “dead” because nothing references it, while secondKotlinStorage is not because it is referenced by firstSwiftStorage.
  2. First GC cycle starts, and firstKotlinStorage is collected.
  3. There are no references to firstSwiftStorage, so it is “dead” as well, and deinit is called.
  4. Second GC cycle starts. secondKotlinStorage is collected because firstSwiftStorage is no longer referencing it.
  5. secondSwiftStorage is finally reclaimed.

It requires two GC cycles to collect these four objects because deinitialization of Swift and Objective-C objects happens after the GC cycle. The limitation stems from deinit, which can call arbitrary code, including the Kotlin code that cannot be run during the GC pause.

Support for background state and App Extensions

The current memory manager does not track application state by default and does not integrate with App Extensions out of the box.

It means that the memory manager doesn’t adjust GC behavior accordingly, which might be harmful in some cases. To change this behavior, add the following Experimental binary option to your gradle.properties:

  1. kotlin.native.binary.appStateTracking=enabled

It turns off a timer-based invocation of the garbage collector when the application is in the background, so GC is called only when memory consumption becomes too high.