蓝色天空网mbsky.com · 知识 · 实践 · 创造Swift · 本地阅读预览
教程 / 移动开发 / Swift

Swift 自动引用计数

系统核对 Swift 自动引用计数(ARC)强引用生命周期、对象间循环强引用泄漏、weak 弱引用自动置 nil、unowned 无主引用生命周期约束,以及逃逸闭包循环引用与 [weak self] + guard let self 化解方案。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

ARC 工作原理与强引用计数

自动引用计数(ARC)是 Swift 用来管理**类实例**内存的核心机制(结构体与枚举为值类型,不参与引用计数)。编译器在编译期自动插入引用计数增减代码:每新增一个强引用计数加一,每断开一个强引用计数减一,计数归零时立即调用 `deinit` 并回收内存。

默认声明的变量引用均为强引用。若 `ref1`、`ref2`、`ref3` 同时指向同一对象,引用计数升至 `3`;依次把 `ref1` 与 `ref2` 置为 `nil` 后计数降至 `1`,实例仍保持存活;直到 `ref3 = nil` 令计数归零,ARC 才自动调用 `deinit`(`deinit` 不可手动调用也不可抛错)。

循环强引用与 weak / unowned 破环

ARC 无法自动回收环状强引用(retain cycle):当 `Person` 强引用 `Apartment` 且 `Apartment` 又强引用 `Person` 时,即使把外部局部变量全部置为 `nil`,两对象内部仍互相持有使引用计数保持为 `1`,`deinit` 永远不会触发,造成内存泄漏。化解思路是将环中至少一端改为非拥有关系:`weak` 或 `unowned`。

弱引用(`weak`)不增加引用计数,并在目标对象销毁时由运行时自动置为 `nil`,因此必须声明为 `var` 的可选类型。将 `Apartment.tenant` 改为 `weak var tenant: Person?` 后,释放 `Person` 时 `tenant` 自动归零为 `nil`,随后释放 `Apartment` 双方均顺利调用 `deinit`;`weak` 广泛适用于代理(delegate)、子节点回指父节点与缓存场景。

无主引用(`unowned`)同样不增加引用计数,但假定目标对象的生命周期始终不短于当前引用者,因而可以是 `let` 且非可选(典型如 `CreditCard` 持有 `unowned let customer: Customer`)。释放 `Customer` 时关联的 `CreditCard` 随之级联释放;但若目标已释放仍强行读取 `unowned` 引用,程序会立即触发运行时崩溃。不确定生命周期边界时,应一律优先选择更安全的 `weak`。

闭包循环引用与捕获列表 [weak self]

闭包作为引用类型会自动捕获其体内访问的外部变量与 `self`。一旦类实例(如 `Reporter`)将闭包存入存储属性或 `lazy var` 属性,而闭包又默认强捕获 `self`,就会形成 `实例 -> 闭包 -> 实例` 的闭环,导致把实例变量置 `nil` 后依然无法销毁。

破解闭包循环的标准方式是在闭包开头声明捕获列表 `[weak self]`,随后在闭包体内以 Swift 5.7+ 的同名简写 `guard let self else { return ... }` 解包(无返回值直接 `return`,有返回值则返回兜底值如 `"对象已释放"`)。仅当闭包会被属性持有或逃逸存活于作用域外时才需要捕获列表,像 `map`、`sorted` 这类同步执行完即销毁的非逃逸闭包不会形成循环引用。

内存泄漏排查高频问答

排查 ARC 问题需把握四点:存储或逃逸闭包访问 `self` 时须配捕获列表,同步高阶函数闭包一般无需;`[weak self]` 将 `self` 变为可选类型,故常配合 `guard let self` 一次解包;目标可能提前释放选 `weak`,生命周期严格绑定选 `unowned`;ARC 只维护计数而不做全局环检测,定位真实内存泄漏需借助 Xcode Memory Graph 或 Instruments 的 Leaks 模板。本站离线 ARC 堆模拟器已完整核验强引用计数、循环泄漏、`weak` 自动置空、`unowned` 悬垂崩溃与闭包捕获列表。

Swift 三种引用方式特性对比

引用方式增加引用计数声明要求目标释放后适用场景
强引用是无特殊修饰,默认即为强引用目标保持存活不会被释放常规所有权持有
弱引用 weak否必须声明为 var 可选类型运行时自动安全置为 nil目标可能先释放(如 delegate、回指)
无主引用 unowned否可为 let 且允许非可选再访问将直接触发运行时崩溃目标生命周期严格不短于引用者

闭包捕获列表对 self 语义的影响

捕获列表闭包与 self 的关系self 的类型适用场景
不写强引用,逃逸存储易引发环Self非逃逸同步闭包或确认无回环
[weak self]弱引用,不增加引用计数Self?self 可能早于闭包释放(推荐默认)
[unowned self]无主引用,不增加引用计数Self明确保证 self 生命周期不短于闭包

运行离线 Python 校验:Swift ARC 引用计数、循环强引用泄漏、weak/unowned 破环与 [weak self]

python · 阅读源码
"""Offline CPython 3.12.14 semantic verifier for Swift ARC (CH29)."""
import json


class DanglingUnownedError(RuntimeError):
    pass


class ARCHeap:
    def __init__(self) -> None:
        self.strong: dict[str, int] = {}
        self.slots: dict[str, dict] = {}
        self.weak_backrefs: dict[str, list[tuple[str, str]]] = {}
        self.deinit_cb: dict[str, object] = {}
        self.events: list[str] = []

    def alloc(self, oid: str, label: str, fields: dict | None = None) -> str:
        self.strong[oid] = 1
        self.slots[oid] = dict(fields or {})
        self.weak_backrefs[oid] = []
        self.deinit_cb[oid] = lambda lbl=label: self.events.append(f"{lbl} 被销毁")
        self.events.append(f"{label} 被创建")
        return oid

    def retain(self, oid: str | None) -> str | None:
        if oid is not None and oid in self.strong:
            self.strong[oid] += 1
        return oid

    def set_strong(self, owner: str, field: str, target: str | None) -> None:
        old = self.slots[owner].get(field)
        if isinstance(old, tuple) and old[0] == "strong":
            self.release(old[1])
        self.slots[owner][field] = ("strong", self.retain(target)) if target else None

    def set_weak(self, owner: str, field: str, target: str | None) -> None:
        self.slots[owner][field] = ("weak", target) if target else None
        if target is not None:
            self.weak_backrefs[target].append((owner, field))

    def set_unowned(self, owner: str, field: str, target: str) -> None:
        self.slots[owner][field] = ("unowned", target)

    def read_weak(self, owner: str, field: str) -> str | None:
        val = self.slots[owner].get(field)
        if not val:
            return None
        return val[1]

    def read_unowned(self, owner: str, field: str) -> str:
        _, target = self.slots[owner][field]
        if target not in self.strong:
            raise DanglingUnownedError(f"Attempted to read deallocated unowned object {target}")
        return target

    def release(self, oid: str | None) -> None:
        if oid is None or oid not in self.strong:
            return
        self.strong[oid] -= 1
        if self.strong[oid] == 0:
            cb = self.deinit_cb.pop(oid)
            fields = self.slots.pop(oid)
            self.strong.pop(oid)
            # Zero all weak references pointing to oid
            for w_owner, w_field in self.weak_backrefs.pop(oid, []):
                if w_owner in self.slots:
                    self.slots[w_owner][w_field] = None
            cb()
            for v in fields.values():
                if isinstance(v, tuple) and v[0] == "strong":
                    self.release(v[1])


def case_arc_refcount_lifecycle():
    heap = ARCHeap()
    ref1 = heap.alloc("s1", "SiteObj")
    ref2 = heap.retain(ref1)
    ref3 = heap.retain(ref1)
    rc_peak = heap.strong["s1"]
    heap.release(ref1)
    heap.release(ref2)
    rc_one = heap.strong["s1"]
    heap.release(ref3)
    alive_after = "s1" in heap.strong
    actual = {
        "peak_refcount": rc_peak,
        "after_two_releases": rc_one,
        "alive_after_last_release": alive_after,
        "events": heap.events,
    }
    expected = {
        "peak_refcount": 3,
        "after_two_releases": 1,
        "alive_after_last_release": False,
        "events": ["SiteObj 被创建", "SiteObj 被销毁"],
    }
    return {
        "name": "arc_refcount_lifecycle",
        "summary": "Verify ARC strong count increments on assignment (1->3) and triggers deinit exactly when count hits 0.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_strong_retain_cycle_leak():
    heap = ARCHeap()
    p = heap.alloc("p1", "Alice")
    apt = heap.alloc("a1", "公寓 A-101")
    heap.set_strong(p, "apartment", apt)
    heap.set_strong(apt, "tenant", p)
    heap.release(p)
    heap.release(apt)
    actual = {
        "events": heap.events,
        "leaked_counts": {"p1": heap.strong.get("p1", 0), "a1": heap.strong.get("a1", 0)},
    }
    expected = {
        "events": ["Alice 被创建", "公寓 A-101 被创建"],
        "leaked_counts": {"p1": 1, "a1": 1},
    }
    return {
        "name": "strong_retain_cycle_leak",
        "summary": "Verify mutual strong references between Person and Apartment leave both refcounts at 1 with zero deinit events.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_weak_and_unowned_cycle_breaking():
    # weak breaks Person <-> Apartment cycle
    heap1 = ARCHeap()
    p = heap1.alloc("p1", "Alice")
    apt = heap1.alloc("a1", "公寓 A-101")
    heap1.set_strong(p, "apartment", apt)
    heap1.set_weak(apt, "tenant", p)
    heap1.release(p)
    tenant_after_person_gone = heap1.read_weak(apt, "tenant")
    heap1.release(apt)

    # unowned breaks Customer <-> CreditCard cycle
    heap2 = ARCHeap()
    c = heap2.alloc("c1", "客户 Alice", {"name": "Alice"})
    card = heap2.alloc("k1", "信用卡 6222-0000")
    heap2.set_strong(c, "card", card)
    heap2.set_unowned(card, "customer", c)
    owner_name = heap2.slots[heap2.read_unowned(card, "customer")]["name"]
    # Keep extra local strong ref to card to test dangling unowned trap separately
    heap2.release(card)  # local card ref released; customer still holds card
    heap2.release(c)     # customer deinit releases card -> both deinit

    # Dangling unowned trap test
    heap3 = ARCHeap()
    c3 = heap3.alloc("c3", "客户 Bob")
    k3 = heap3.alloc("k3", "信用卡 9999")
    heap3.set_unowned(k3, "customer", c3)
    heap3.release(c3)
    unowned_trapped = False
    try:
        heap3.read_unowned(k3, "customer")
    except DanglingUnownedError:
        unowned_trapped = True

    actual = {
        "weak_tenant_zeroed": tenant_after_person_gone is None,
        "weak_events": heap1.events,
        "unowned_owner_name": owner_name,
        "unowned_events": heap2.events,
        "dangling_unowned_trapped": unowned_trapped,
    }
    expected = {
        "weak_tenant_zeroed": True,
        "weak_events": ["Alice 被创建", "公寓 A-101 被创建", "Alice 被销毁", "公寓 A-101 被销毁"],
        "unowned_owner_name": "Alice",
        "unowned_events": ["客户 Alice 被创建", "信用卡 6222-0000 被创建", "客户 Alice 被销毁", "信用卡 6222-0000 被销毁"],
        "dangling_unowned_trapped": True,
    }
    return {
        "name": "weak_and_unowned_cycle_breaking",
        "summary": "Verify weak auto-zeros to nil to break retain cycle, unowned cascades deinit, and reading a deallocated unowned ref traps.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_closure_capture_cycle_and_weak_self():
    # 1. Strong capture leaks
    heap_leak = ARCHeap()
    rep = heap_leak.alloc("r1", "Reporter", {"site": "example.com"})
    clo = heap_leak.alloc("cl1", "StrongClosure")
    heap_leak.set_strong(rep, "onFinish", clo)
    heap_leak.set_strong(clo, "captured_self", rep)
    heap_leak.release(clo)
    heap_leak.release(rep)
    leaked = "r1" in heap_leak.strong

    # 2. [weak self] + guard let self breaks cycle
    heap_ok = ARCHeap()
    rep2 = heap_ok.alloc("r2", "Reporter", {"site": "example.com"})
    clo2 = heap_ok.alloc("cl2", "WeakClosure")
    heap_ok.set_strong(rep2, "onFinish", clo2)
    heap_ok.set_weak(clo2, "captured_self", rep2)

    def invoke_closure():
        target = heap_ok.read_weak(clo2, "captured_self")
        if target is None:
            return "对象已释放"
        return f"站点:{heap_ok.slots[target]['site']}"

    before_nil = invoke_closure()
    heap_ok.release(rep2)
    after_nil = invoke_closure()
    heap_ok.release(clo2)

    actual = {
        "strong_closure_leaked": leaked,
        "weak_closure_before_nil": before_nil,
        "weak_closure_after_nil": after_nil,
        "weak_reporter_deallocated": "r2" not in heap_ok.strong,
    }
    expected = {
        "strong_closure_leaked": True,
        "weak_closure_before_nil": "站点:example.com",
        "weak_closure_after_nil": "对象已释放",
        "weak_reporter_deallocated": True,
    }
    return {
        "name": "closure_capture_cycle_and_weak_self",
        "summary": "Verify escaping closure strong capture leaks Reporter while [weak self] + guard let self allows deinit and returns fallback.",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main() -> None:
    report = {
        "version": "CPython 3.12.14 offline Swift 5/6 semantic verifier (swiftc absent)",
        "cases": [
            case_arc_refcount_lifecycle(),
            case_strong_retain_cycle_leak(),
            case_weak_and_unowned_cycle_breaking(),
            case_closure_capture_cycle_and_weak_self(),
        ],
    }
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 核对强引用计数 3->1->0 销毁、Person<->Apartment 泄漏计数 1、weak 自动归零、unowned 级联释放与悬垂异常,以及闭包 [weak self] 安全返回“对象已释放”。
运行离线 Python 校验:Swift ARC 引用计数、循环强引用泄漏、weak/unowned 破环与 [weak self]

所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

当前源码 SHA256:cf7437630f745addfc4566ab11d26850b6f4da337384515f373bad5c1cb57272

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载Swift 自动引用计数实验

所需环境:Windows x64、CPython 3.12.14 离线 Swift 5/6 语义校验器(本机未安装 swiftc / Xcode / SwiftPM)。

ZIP SHA256:99c73f445096a7f6e14164850ac733deca2efdf7b90b8ee7ae1a580201c144ee

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么 weak 引用必须声明为 var 可选类型,而 unowned 可以声明为 let 非可选类型?

展开参考解答

因为 weak 引用指向的目标被释放后,ARC 运行时会在运行期把该变量自动修改为 nil,所以它必须既可变(var)又能容纳 nil(可选);而 unowned 假定目标在自身存活期内永不被释放且永不置 nil,因此可用 let 非可选声明。

规范与官方依据