DEV Community

Cover image for Swift Mastery Series — Part 15: ARC & Memory Management
divyesh vekariya
divyesh vekariya

Posted on Originally published at Medium

Swift Mastery Series — Part 15: ARC & Memory Management

ARC & Memory Management in Swift

ARC handles much of Swift's memory management for us.

But you still need to understand:

  • Strong references
  • Reference cycles
  • weak vs unowned
  • Closures and object lifetimes
  • Common memory leaks

Understanding ownership makes debugging memory issues much easier.

https://medium.com/@dkvekariya/2e9af2ea677f

swift #ios #swiftui

Top comments (1)

Collapse
 
traceypears profile image
traceypears •

ARC với closure capture list là nơi dễ bị "lừa" nhất — đặc biệt khi mix weak self với async/await. Pattern hay gặp:

Task { [weak self] in
    await self?.fetchData()
}
Enter fullscreen mode Exit fullscreen mode

Nếu self bị dealloc giữa await, closure vẫn resume nhưng self là nil → silent no-op. Khó debug vì không crash, chỉ mất dữ liệu lặng lẽ.

Cách an toàn hơn: capture strong reference cục bộ bên trong task, check guard let self = self else { return } ngay sau await đầu tiên. Hoặc dùng withTaskCancellationHandler để cleanup explicit khi task bị cancel.

Một cái bẫy khác: unowned với @MainActor isolated property. Nếu object dealloc trên background thread mà property vẫn được truy cập từ main actor → EXC_BAD_ACCESS. weak + guard let vẫn an toàn nhất, dù verbose hơn.

Xcode 16 có diagnostic mới cho retain cycle trong @MainActor context —值得 bật SWIFT_ENABLE_ACTOR_ISOLATION_CHECKS để catch sớm PS: the tool I meant is on labagent .tech