-
ARC: Resolving Strong Reference Cycles Between Class Instancesios 2020. 9. 7. 23:41
들어가며
이 전 글은 ARC에 대해서 알아보았습니다. 오늘은 Strong Reference로 인한 Retain Cycle을 어떻게 해결하면 좋을지에 대해서 알아보도록 하겠습니다.
Resolving Strong Reference Cycles Between Class Instances
Swift provides two ways to resolve strong reference cycles when you work with properties of class type: weak references and unowned references.
Weak and unowned references enable one instance in a reference cycle to refer to the other instance without keeping a strong hold on it. The instances can then refer to each other without creating a strong reference cycle.
- swift에서는 reference cycle 을 해결하기 위해 weak 와 unowned 두 가지 방법을 제공합니다.
- weak 와 unowned reference는 reference cycle에서 특정 인스턴스가 다른 인스턴스를 참조하는데 strong reference로 잡고 있지 않다는 뜻 입니다.
- 이 말은 즉, strong reference를 만들지 않더라도 서로 참조할 수 있다는 말입니다.
Weak
A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak keyword before a property or variable declaration.
- weak reference는 참조하는 인스턴스를 강력하게 잡고 있지 않는 참조 이므로 ,
- ARC는 참조된 인스턴스를 처리하는데 중지하지 않는다고 합니다. ( 이 부분은 제가 잘 해석한지 모르겠습니다..)
- 이 행동은 strong referennce이 한 부분이 되는 것을 막습니다.
- 변수 선언에 앞서 weak 키워드를 작성해야 합니다
Because a weak reference does not keep a strong hold on the instance it refers to, it’s possible for that instance to be deallocated while the weak reference is still referring to it. Therefore, ARC automatically sets a weak reference to nil when the instance that it refers to is deallocated. And, because weak references need to allow their value to be changed to nil at runtime, they are always declared as variables, rather than constants, of an optional type.
- weak reference는 특정 인스턴스를 강력하게 잡고 참조하지 않기 때문에 , weak reference가 참조하고 있는 경우에도 참조된 reference를 메모리에서 해제 시킬 수 있다고 합니다.
- 참조 되었던 reference가 메모리에서 해제 된 경우, 자동적으로 weak reference는 nil로 초기화 됩니다.
- 그래서 weak reference는 항상 optional 이여야 합니다.
- 그 이유는 , 실행중에 참조하고 있는 객체가 언제 메모리에서 해제될지 모르기 때문입니다.
You can check for the existence of a value in the weak reference, just like any other optional value, and you will never end up with a reference to an invalid instance that no longer exists.
- weak reference는 다른 optional value 처럼 사용할 때 존재 여부를 확인해야 합니다.
EXAMPLE
weak reference example 위 예제는 강한 참조 순환 문제를 weak로 해결하는 가장 이상적인 예제라고 합니다. 위 상황은 Person 클래스 , Apartment 클래스가 주어지고 Apartment 내 tenant 프로퍼티를 weak로 지정해 두었습니다. 그 이유는 Apartment가 tenant를 가지고 있을 경우도 있고 없을 경우도 있기 때문이지요.
The Person instance still has a strong reference to the Apartment instance, but the Apartment instance now has a weak reference to the Person instance. This means that when you break the strong reference held by the john variable by setting it to nil, there are no more strong references to the Person instance:
- Person instance는 Apartmennt instance를 strong하게 참조하고 있습니다.
- 이로 인해 , Apartment instance의 ARC 는 2가 되었으며,
- Apartmennt Instance는 Person instance를 weak reference로 설정해 두었기 때문에
- Person Instance ARC 는 1이 됩니다. (단 ,ARC 는 strong reference 만을 카운트 합니다.)
- person instance를 nil 처리를 통해 dealloc을 시킨다면 ,
- Person ARC는 1 -> 0 이 됩니다.
- Person이 참조하던 Apartment ARC는 2 -> 1 로 변경 됩니다.
john = nil 처리 결국 , Apartment ARC 는 1이 남게 되고, unit4A = nil 처리를 해준다면 "Apartment 4A is being deinitialized" Apartment의 deInit이 호출 될 것입니다.
마치며
strong reference cycle 문제가 생긴다면, 상황에 따라 다르 겠지만 참조하고 있는 인스턴스의 라이프 사이클이 참조하고 있는 인스턴스보다 짧을 경우 경우에는 weak를 사용하여 문제를 해결할 수 있는 방법을 이번 포스팅을 하면서 알게 되었습니다.
다음에는 unowned를 다루어 보겠습니다.
읽어주셔서 감사합니다.
'ios' 카테고리의 다른 글
custom font 적용 (0) 2021.10.25 로컬 푸시 알림 기능 구현 (Local Notification) (0) 2020.12.17 ARC (0) 2020.09.06 네트워크 통신 모듈화 with Alamofire (0) 2020.07.21 APNs 사용법 (0) 2020.07.20