본문 바로가기
Dev Log/iOS

[Swift] Automatic Reference Counting 내용 요약

by 삽질하는큐 2018. 3. 16.

Official Document:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html


  ARC. Automatic Reference Counting. ARC class 인스턴스가 할당될 때부터 메모리 상태를 추적한다. (struct, enum 해당하지 않는다.) class 내의 property, constant, variables 이상 사용되지 않을 메모리를 해제하게 된다. 평상시에는 별다른 조취를 취하지 않아도 메모리를 해제하게 되지만, 이상의 인스턴스가 서로를 참조하고 있을 경우(strong reference cycle) 메모리 해제 대상이 아니다.


  상호 참조를 해야하는 경우가 발생한다면 weak이나 unowned 키워드를 사용해서 strong reference cycle 방지할 있다

- weak 객체 A보다 참조되는 객체 B 오래 남아있어야 필요가 없을 사용한다

- unowned 객체 A보다 참조되는 객체 B 오래 남아있거나 동시에 해제될 사용한다

따라서 strong reference cycle 예상되는 property 선언할 앞에 weak이나 unowned 명시하는 것이 좋다. unowned nil 없을 것이라고 가정하기 때문에 optional 타입을 지원하지 않는다. nil 있는 인스턴스에는 weak 쓰고 nil 없는 인스턴스에는 unowned 쓴다.

*unowned(unsafe) 라는 키워드도 있지만, Cocoa class import wrapper에서나 있을 것이고 쓰지 않는 것이 좋다.


  closure reference type이기 때문에 ARC 메모리 상태를 추적하게 된다. closure instance method 아니라서 input type return type 같다면 재정의가 가능한데, 이럴 다른 reference type 참조할 경우가 생긴다. 때도 unowned weak 쓰면 되고, 자기 자신의 property 접근하게 경우 unowned self 쓰면 좋다. closure 내에 unowned weak 정의하는 것을 capture list라고 한다.


'Dev Log > iOS' 카테고리의 다른 글

Apple Login (Sign In With Apple) 구현하기  (0) 2020.02.23