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
-
weakvsunowned - Closures and object lifetimes
- Common memory leaks
Understanding ownership makes debugging memory issues much easier.
https://medium.com/@dkvekariya/2e9af2ea677f
Top comments (1)
ARC với closure capture list là nơi dễ bị "lừa" nhất — đặc biệt khi mix
weak selfvới async/await. Pattern hay gặp:Nếu
selfbị dealloc giữaawait, closure vẫn resume nhưngselflà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
strongreference cục bộ bên trong task, checkguard let self = self else { return }ngay sauawaitđầu tiên. Hoặc dùngwithTaskCancellationHandlerđể cleanup explicit khi task bị cancel.Một cái bẫy khác:
unownedvới@MainActorisolated 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 letvẫn an toàn nhất, dù verbose hơn.Xcode 16 có diagnostic mới cho retain cycle trong
@MainActorcontext —值得 bậtSWIFT_ENABLE_ACTOR_ISOLATION_CHECKSđể catch sớm PS: the tool I meant is on labagent .tech