본문 바로가기
Swift

[Swift] Weak vs Unowned Reference

by Sky Titan 2022. 8. 20.
728x90
 

ARC and Memory Management in Swift

In this tutorial, you’ll learn how ARC works and how to code in Swift for optimal memory management. You’ll learn what reference cycles are, how to use the Xcode 10 visual debugger to discover them when they happen and how to break them using an exampl

www.raywenderlich.com

Weak vs Unowned Reference

  • 둘 다 strong reference와 다르게 객체의 reference count를 증가시키지 않는다.
  • 즉, 객체의 lifecycle 관리에 관여하지 않는다.
  • Weak Reference는 언제나 'Optional type'이여야 하고, reference count가 0이 되면 참조가 nil이 될 수 있다.
    • 참조가 nil로 변할 수 있어야 되기 때문에 let으로 선언이 불가하고 항상 var로만 선언이 가능하다.
  • Unowned Reference는 Weak와 다르게 항상 'Non-Optional type'이다.
    • 때문에 deinitialize된 unowned 객체에 접근하면 runtime error가 발생한다.
  var let optional non-optional
Strong O O O O
Weak O X O X
Unowned O O X O
728x90

댓글