This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
mobilecritical PriorityID: kmp-arc-retain-cycle-elimination-native-ios

Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes

Enforces strict boundary lifecycle decoupling between Swift ARC and Kotlin/Native garbage-collected runtimes. Bidirectional cross-runtime strong references prevent deallocation across runtime boundaries, creating permanent memory leaks and triggering iOS jetsam background termination crashes.

Prohibited Anti-Pattern: Bidirectional Strong Bridging Between Swift ARC Delegates and Kotlin/Native Observables

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes - Enforces strict boundary lifecycle decoupling between Swift ARC and Kotlin/Native garbage-collected runtimes. Bidirectional cross-runtime strong references prevent deallocation across runtime boundaries, creating permanent memory leaks and triggering iOS jetsam background termination crashes.
globs: iosApp/**/*.{swift,m,h}, shared/src/iosMain/**/*.kt, shared/src/commonMain/**/*.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/kmp-arc-retain-cycle-elimination-native-ios"
---

# Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Bidirectional Strong Bridging Between Swift ARC Delegates and Kotlin/Native Observables

## System Constraints
You are a Principal Mobile Architect enforcing absolute memory safety between Kotlin/Native and Apple Swift/Objective-C ARC runtimes. You must eliminate all inter-runtime retain cycles by enforcing weak reference patterns, explicit cancellation lifecycle contracts, and proper boundary encapsulation.

## Strict Guidelines
- Engineers MUST ALWAYS use weak references (`[weak self]`) within Swift closures or callbacks capturing Swift objects that subscribe to Kotlin Flows, Coroutines, or long-lived native bridges.
- Engineers MUST NOT store strong references to Swift delegate interfaces or platform-native callbacks inside long-lived Kotlin singletons or ViewModels; use `kotlin.native.ref.WeakReference` or pass execution scopes explicitly.
- Swift classes bridging Kotlin ViewModels MUST cancel and nullify active Kotlin coroutine collectors (`Job` or `Closeable`/`Cancellable`) inside `deinit`.
- Kotlin-exported interfaces intended for iOS delegate patterns MUST be designated as weak-compatible or require non-owning registration topologies.
- Components NEVER bridge unbounded Kotlin `SharedFlow` or `StateFlow` collection into Swift UI structs/classes without binding collection lifecycles to `View.onDisappear` or `Task` cancellation.

## Bad vs Good Implementations
### Swift Collector Observing Kotlin StateFlow

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Kotlin's collector holds a strong reference to the Swift closure, which strongly captures 'self' (UserProfileViewModel). Meanwhile, UserProfileViewModel holds a strong reference to SharedUserProfileViewModel. Neither Swift ARC nor Kotlin GC can collect this cycle, resulting in a persistent leak.
```swift
class UserProfileViewModel: ObservableObject {
    private let kotlinViewModel = SharedUserProfileViewModel()
    @Published var state: UserState = .initial

    init() {
        // CRITICAL BUG: Strong reference cycle between Swift closure and Kotlin collector
        kotlinViewModel.stateFlow.collect { [self] newState in
            self.state = newState
        }
    }
}
```

#### Production Standard (Correct)
> **Standard**: Using '[weak self]' prevents the closure retained by Kotlin from holding 'UserProfileViewModel' alive. Exposing an explicit 'dispose()' hook allows 'deinit' to cleanly tear down the cross-runtime bridge.
```swift
class UserProfileViewModel: ObservableObject {
    private let kotlinViewModel = SharedUserProfileViewModel()
    private var cancellableJob: KmpCancellable? = nil
    @Published var state: UserState = .initial

    init() {
        // Invariant: Weak capture of self and explicit cancellable handle retain
        self.cancellableJob = kotlinViewModel.stateFlow.collectDisposable { [weak self] newState in
            guard let self = self else { return }
            self.state = newState
        }
    }

    deinit {
        // Invariant: Explicitly dispose bridge on ARC deallocation
        cancellableJob?.dispose()
        cancellableJob = nil
    }
}
```

### Kotlin Native Bridge Holding iOS Delegate

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the native iOS listener class retains the AudioEngineBridge instance, holding a direct strong Kotlin reference to that listener creates an inter-runtime retain cycle.
```kotlin
package com.example.shared

interface NativeAudioListener {
    fun onPlaybackProgress(seconds: Double)
}

class AudioEngineBridge {
    // CRITICAL BUG: Strong reference to native iOS listener creates permanent ARC-GC graph
    var listener: NativeAudioListener? = null

    fun tick(time: Double) {
        listener?.onPlaybackProgress(time)
    }
}
```

#### Production Standard (Correct)
> **Standard**: Uses 'kotlin.native.ref.WeakReference' on the Native boundary to ensure Kotlin does not prevent Swift ARC from releasing the listener.
```kotlin
package com.example.shared

import kotlin.native.ref.WeakReference

interface NativeAudioListener {
    fun onPlaybackProgress(seconds: Double)
}

class AudioEngineBridge {
    private var listenerRef: WeakReference<NativeAudioListener>? = null

    var listener: NativeAudioListener?
        get() = listenerRef?.get()
        set(value) {
            listenerRef = value?.let { WeakReference(it) }
        }

    fun tick(time: Double) {
        listener?.onPlaybackProgress(time)
    }

    fun clear() {
        listenerRef = null
    }
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes

Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes defines an industrial-grade behavioral standard for mobile engineering. Enforces strict boundary lifecycle decoupling between Swift ARC and Kotlin/Native garbage-collected runtimes. Bidirectional cross-runtime strong references prevent deallocation across runtime boundaries, creating permanent memory leaks and triggering iOS jetsam background termination crashes. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Bidirectional Strong Bridging Between Swift ARC Delegates and Kotlin/Native Observables Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftBidirectional Strong Bridging Between Swift ARC Delegates and Kotlin/Native ObservablesCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use weak references (`[weak self]`) within Swift closures or callbacks capturing Swift objects that subscribe to Kotlin Flows, Coroutines, or long-lived native bridges.

Engineers MUST ALWAYS use weak references (`[weak self]`) within Swift closures or callbacks capturing Swift objects that subscribe to Kotlin Flows, Coroutines, or long-lived native bridges.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT store strong references to Swift delegate interfaces or platform-native callbacks inside long-lived Kotlin singletons or ViewModels

Engineers MUST NOT store strong references to Swift delegate interfaces or platform-native callbacks inside long-lived Kotlin singletons or ViewModels; use `kotlin.native.ref.WeakReference` or pass execution scopes explicitly.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Swift classes bridging Kotlin ViewModels MUST cancel and nullify active Kotlin coroutine collectors (`Job` or `Closeable`/`Cancellable`) inside `deinit`.

Swift classes bridging Kotlin ViewModels MUST cancel and nullify active Kotlin coroutine collectors (`Job` or `Closeable`/`Cancellable`) inside `deinit`.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Kotlin-exported interfaces intended for iOS delegate patterns MUST be designated as weak-compatible or require non-owning registration topologies.

Kotlin-exported interfaces intended for iOS delegate patterns MUST be designated as weak-compatible or require non-owning registration topologies.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER bridge unbounded Kotlin `SharedFlow` or `StateFlow` collection into Swift UI structs/classes without binding collection lifecycles to `View.onDisappear` or `Task` cancellation.

Components NEVER bridge unbounded Kotlin `SharedFlow` or `StateFlow` collection into Swift UI structs/classes without binding collection lifecycles to `View.onDisappear` or `Task` cancellation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Kotlin Multiplatform ARC Retain-Cycle Elimination in Native iOS Runtimes critical for AI coding assistants?

Enforces strict boundary lifecycle decoupling between Swift ARC and Kotlin/Native garbage-collected runtimes. Bidirectional cross-runtime strong references prevent deallocation across runtime boundaries, creating permanent memory leaks and triggering iOS jetsam background termination crashes. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Bidirectional Strong Bridging Between Swift ARC Delegates and Kotlin/Native Observables) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related MOBILE Rules

View all rules →
1 Rule in Stack

Kotlin