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

Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail

Enforces strict weak-reference bridging and explicit lifecycle-bound teardown contracts between native UIKit/AppKit views and Kotlin/Native composables embedded via ComposeUIViewController. Without explicit weak referencing and onDispose cleanup callbacks, cross-runtime retain cycles between Apple ARC and Kotlin/Native garbage collector will cause permanent memory leaks.

Prohibited Anti-Pattern: Cross-Runtime ARC Strong Retain Cycles via Closure Captures and Missing Teardown Callbacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail - Enforces strict weak-reference bridging and explicit lifecycle-bound teardown contracts between native UIKit/AppKit views and Kotlin/Native composables embedded via ComposeUIViewController. Without explicit weak referencing and onDispose cleanup callbacks, cross-runtime retain cycles between Apple ARC and Kotlin/Native garbage collector will cause permanent memory leaks.
globs: **/iosMain/**/*.kt, **/iosApp/**/*.swift, **/commonMain/**/UIKitInterop*.kt, **/iosMain/**/*ViewController.kt
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/cmp-ios-arc-retain-cycle-memory-guardrail"
---

# Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail

> **Severity**: CRITICAL | **Category**: mobile
> **Anti-Pattern Warning**: Cross-Runtime ARC Strong Retain Cycles via Closure Captures and Missing Teardown Callbacks

## System Constraints
You are a Principal Mobile Architect specializing in Kotlin Multiplatform and iOS native runtime interoperability. Your role is to mandate strict memory-management invariants at the boundary between Kotlin/Native and Swift/Objective-C ARC. You must reject any code that directly captures native UIKit/AppKit instances inside Compose state holders or closures without explicit weak references, and enforce deterministic DisposableEffect disposal for UIKitView/UIKitViewController integrations to prevent leaked view hierarchies.

## Strict Guidelines
- Engineers MUST ALWAYS use weak references (via `WeakReference` in Kotlin or `[weak self]` in Swift) when bridging callbacks across the Kotlin/Native and Swift ARC boundary.
- Engineers MUST ALWAYS implement deterministic cleanup in `UIKitView` or `UIKitViewController` using the `onReset` parameter or Compose `DisposableEffect` to sever delegate and listener references upon composition disposal.
- Engineers MUST NOT capture strong references to native `UIView`, `UIViewController`, or native delegating coordinator instances inside long-lived Kotlin coroutine scopes, ViewModel instances, or remember blocks.
- Code SHOULD wrap native view controllers using `UIKitViewController` instead of raw `UIKitView` whenever the embedded component participates in navigation or lifecycle events.
- Components NEVER store lambda callbacks that capture enclosing Kotlin composable state directly on Objective-C / Swift native delegates without an intermediary zeroing weak wrapper.

## Bad vs Good Implementations
### UIKitView Native Map Integration with Proper ARC Teardown

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The native MKMapView retains the LeakyMapDelegate instance via its delegate property, while the delegate captures the Kotlin closure which references the Compose scope. Neither delegate detachment nor view teardown is specified, leading to an ARC-Kotlin cross-boundary retain cycle that leaks the native view hierarchy when the composable leaves composition.
```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.ui.interop.UIKitView
import platform.MapKit.MKMapView
import platform.MapKit.MKMapViewDelegateProtocol
import platform.darwin.NSObject

class LeakyMapDelegate(private val onLocationChanged: (Double, Double) -> Unit) : NSObject(), MKMapViewDelegateProtocol {
    // Strong reference retention across runtimes
}

@Composable
fun MapComponent(onPositionUpdate: (Double, Double) -> Unit) {
    // ANTI-PATTERN: Delegate holds strong closure; MKMapView holds delegate;
    // Compose retains both without onReset or explicit teardown.
    UIKitView(
        factory = {
            val mapView = MKMapView()
            val delegate = LeakyMapDelegate(onPositionUpdate)
            mapView.delegate = delegate
            mapView
        }
    )
}
```

#### Production Standard (Correct)
> **Standard**: Provides deterministic teardown using `onReset` and `onRelease` contracts on UIKitView, breaks the delegate reference, and prevents cross-runtime capture cycles using `rememberUpdatedState` and zeroing references upon disposal.
```kotlin
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.Modifier
import androidx.compose.ui.interop.UIKitView
import platform.MapKit.MKMapView
import platform.MapKit.MKMapViewDelegateProtocol
import platform.darwin.NSObject
import kotlin.native.ref.WeakReference

private class SafeMapDelegate(
    listener: (Double, Double) -> Unit
) : NSObject(), MKMapViewDelegateProtocol {
    private var callbackRef = WeakReference(listener)

    fun updateListener(newListener: (Double, Double) -> Unit) {
        callbackRef = WeakReference(newListener)
    }

    fun clear() {
        callbackRef = WeakReference(null)
    }
}

@Composable
fun MapComponent(modifier: Modifier = Modifier, onPositionUpdate: (Double, Double) -> Unit) {
    val currentCallback by rememberUpdatedState(onPositionUpdate)

    UIKitView(
        factory = {
            val mapView = MKMapView()
            val delegate = SafeMapDelegate(currentCallback)
            mapView.delegate = delegate
            mapView
        },
        modifier = modifier,
        update = {
            (it.delegate as? SafeMapDelegate)?.updateListener(currentCallback)
        },
        onReset = { mapView ->
            (mapView.delegate as? SafeMapDelegate)?.clear()
            mapView.delegate = null
        },
        onRelease = { mapView ->
            (mapView.delegate as? SafeMapDelegate)?.clear()
            mapView.delegate = null
            mapView.removeFromSuperview()
        }
    )
}
```

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: Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail

Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail defines an industrial-grade behavioral standard for mobile engineering. Enforces strict weak-reference bridging and explicit lifecycle-bound teardown contracts between native UIKit/AppKit views and Kotlin/Native composables embedded via ComposeUIViewController. Without explicit weak referencing and onDispose cleanup callbacks, cross-runtime retain cycles between Apple ARC and Kotlin/Native garbage collector will cause permanent memory leaks. 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: Cross-Runtime ARC Strong Retain Cycles via Closure Captures and Missing Teardown Callbacks 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 DriftCross-Runtime ARC Strong Retain Cycles via Closure Captures and Missing Teardown CallbacksCritical
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 (via `WeakReference` in Kotlin or `[weak self]` in Swift) when bridging callbacks across the Kotlin/Native and Swift ARC boundary.

Engineers MUST ALWAYS use weak references (via `WeakReference` in Kotlin or `[weak self]` in Swift) when bridging callbacks across the Kotlin/Native and Swift ARC boundary.

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 ALWAYS implement deterministic cleanup in `UIKitView` or `UIKitViewController` using the `onReset` parameter or Compose `DisposableEffect` to sever delegate and listener references upon composition disposal.

Engineers MUST ALWAYS implement deterministic cleanup in `UIKitView` or `UIKitViewController` using the `onReset` parameter or Compose `DisposableEffect` to sever delegate and listener references upon composition disposal.

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

Engineers MUST NOT capture strong references to native `UIView`, `UIViewController`, or native delegating coordinator instances inside long-lived Kotlin coroutine scopes, ViewModel instances, or remember blocks.

Engineers MUST NOT capture strong references to native `UIView`, `UIViewController`, or native delegating coordinator instances inside long-lived Kotlin coroutine scopes, ViewModel instances, or remember blocks.

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

Code SHOULD wrap native view controllers using `UIKitViewController` instead of raw `UIKitView` whenever the embedded component participates in navigation or lifecycle events.

Code SHOULD wrap native view controllers using `UIKitViewController` instead of raw `UIKitView` whenever the embedded component participates in navigation or lifecycle events.

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 store lambda callbacks that capture enclosing Kotlin composable state directly on Objective-C / Swift native delegates without an intermediary zeroing weak wrapper.

Components NEVER store lambda callbacks that capture enclosing Kotlin composable state directly on Objective-C / Swift native delegates without an intermediary zeroing weak wrapper.

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 Compose Multiplatform iOS Interop ARC Retain-Cycle & Teardown Guardrail critical for AI coding assistants?

Enforces strict weak-reference bridging and explicit lifecycle-bound teardown contracts between native UIKit/AppKit views and Kotlin/Native composables embedded via ComposeUIViewController. Without explicit weak referencing and onDispose cleanup callbacks, cross-runtime retain cycles between Apple ARC and Kotlin/Native garbage collector will cause permanent memory leaks. 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 (Cross-Runtime ARC Strong Retain Cycles via Closure Captures and Missing Teardown Callbacks) 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

Compose