티스토리 뷰

Auto Reference Counting - Part 5

( a.k.a ARC )

 

 

 

Swift 5.0 - The Swift Programming Language (Apple Inc.)  번역 

 

 

 

ARC 1편 - ARC 의 개요와 작동 원리 (https://atelier-chez-moi.tistory.com/37)

ARC 2편 - 강한 순환 참조 (https://atelier-chez-moi.tistory.com/40)

ARC 3편 - 강한 순환 참조 해결하기(1) : 약한 참조 (https://atelier-chez-moi.tistory.com/41)

ARC 4편 - 강한 순환 참조 해결하기(2) : 미소유 참조 (https://atelier-chez-moi.tistory.com/48)

ARC 5편 - 미소유 참조와 암시적 언래핑된 옵셔널 프로퍼티 (현재 글)

 

Unowned References and Implicitly Unwrapped Optional Properties

미소유 참조와 암시적 언래핑된 옵셔널 프로퍼티 


The examples for weak and unowned references above cover two of the more common scenarios in 

which it’s necessary to break a strong reference cycle.

 

앞에서 본 약한 참조와 미소유 참조의 예시는 강한 순환 참조를 부숴야 할 필요가 있는 일반적인 두 가지 시나리오를 다루고 있습니다.


The Person and Apartment example shows a situation where two properties, both of which are allowed to be nil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference.

 

Person 과 Apartment 의 예는 둘 다 nil 을 허용하는 두 프로퍼티가 강한 순환 참조를 유발할 수 있는 상황을 보여줍니다. 이 시나리오는 약한 참조가 최고의 해결책이죠.


The Customer and CreditCard example shows a situation where one property that is allowed to be nil and another property that cannot be nil have the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.

 

Customer 와 CreditCard 예는 하나의 프로퍼티만 nil 을 허용하고 nil 이 될 수 없는 다른 프로퍼티는 강한 순환 참조를 잠재적으로 유발할 수 있습니다. 이 시나리오는 미소유 참조가 최고의 해결책이죠.


However, there is a third scenario, in which both properties should always have a value, and neither property should ever be nil once initialization is complete. 

In this scenario, it’s useful to combine an unowned property on one class with an implicitly unwrapped optional property on the other class.

 

하지만, 세번째 시나리오도 있어요. 두 프로퍼티가 항상 값을 가져야만 하고, 초기화가 끝난 이상은 어느 프로퍼티도 nil 이 되어서는 안됩니다.  이 시나리오에서는 하나의 클래스에서는 미소유 프로퍼티를 다른 클래스 상에서 암시적 언래핑된 옵셔널 프로퍼티와 함께 결합한다면 아주 유용할 겁니다. 


This enables both properties to be accessed directly (without optional unwrapping) once initialization is complete,

 while still avoiding a reference cycle. This section shows you how to set up such a relationship.

 

이것은 순환 참조를 피하면서 초기화가 끝나면 (옵셔널 언래핑 없이) 바로 두 프로퍼티에 직접 엑세스 하는 것을 가능하게 해줍니다.

이 섹션에서는 그러한 관계를 설정하는 방법을 보여줄 거에요.

The example below defines two classes, Country and City, each of which stores an instance of the other class as a property. 

In this data model, every country must always have a capital city, and every city must always belong to a country. 

To represent this, the Country class has a capitalCity property, and the City class has a country property:

 

아래 예시는 두 클래스 Country 와 City 를 정의하고 있어요. 클래스는 각자 프로퍼티로 다른 클래스의 인스턴스를 저장하고 있어요. 데이터 모델에서, 모든 국가는 항상 수도를 가져야만 하며, 모든 도시는 항상 국가에 속해야만 합니다. 이것을 나타내기 위해 Country 클래스는 capitalCity 프로퍼티를 가지고, City 클래스는 country 프로퍼티를 가집니다:

 

 

To set up the interdependency between the two classes, the initializer for City takes a Country instance, and stores this instance in its country property.

 

두 클래스 사이의 상호의존성을 설정하기 위해, City 의 이니셜라이저는 Country 인스턴스를 가지며 country 프로퍼티 내에 이 인스턴스를 저장합니다.


The initializer for City is called from within the initializer for Country

However, the initializer for Country cannot pass self to the City initializer until a new Country instance is fully initialized,

 as described in Two-Phase Initialization.

 

City 의 이니셜라이저는 Country 이니셜라이저 내부로부터 호출되요. 그러나, Country 의 이니셜라이저는 새로운 Country 인스턴스가 완전히 초기화될 때까지 자기 자신을 City 이니셜라이저에 전달할 수 없어요 . (참고: Two-Phase Initialization)


To cope with this requirement, you declare the capitalCity property of Country as an implicitly unwrapped optional property, 

indicated by the exclamation mark at the end of its type annotation (City!). 

This means that the capitalCity property has a default value of nil, like any other optional,

 but can be accessed without the need to unwrap its value as described in Implicitly Unwrapped Optionals.

 

이 요구 사항에 대처하기 위해, Country 의 capitalCity 프로퍼티를 암시적 언래핑된 옵셔널 프로퍼티로 선언해요. 타입 어노테이션의 끝에 느낌표로 표시되죠 (City!). 이는 capitalCity 프로퍼티가 다른 옵셔널들 처럼 디폴트 값으로 nil 을 가진다는 것을 의미하지만, Implicitly Unwrapped Optionals 에서 설명된 것처럼, 자신의 값을 언래핑(unwrap)할 필요성 없이 엑세스 할 수 있습니다.    


Because capitalCity has a default nil value, a new Country instance is considered fully initialized as soon as the Country instance sets its name property within its initializer. 

This means that the Country initializer can start to reference and pass around the implicit self property as soon as the name property is set. 

The Country initializer can therefore pass self as one of the parameters for the City initializer when the Country initializer is setting its own capitalCity property.

 

왜냐하면 capitalCity 가 디폴트 값으로 nil 을 가지기 때문에, 새로운 Country 인스턴스는 Country 인스턴스가 자신의 이니셜 라이저 내 name 프로퍼티를 설정하자마자 완전히 초기화 된 것으로 간주됩니다. 이것은 Country 이니셜라이저가 name 프로퍼티를 설정하자마자 암시적 self 프로퍼티를 참조하고 전달 할 수 있습니다. 따라서 Country 이니셜라이저가 자신이 소유한 capitalCity 프로퍼티를 설정할 때, Country 이니셜라이저가 self 를 City 이니셜라이저의 파라미터들 중의 하나로서 전달할 수 있습니다.  


All of this means that you can create the Country and City instances in a single statement, without creating a strong reference cycle, and the capitalCity property can be accessed directly, without needing to use an exclamation mark to unwrap its optional value:

 

이 모든 것은 Country 와 City 인스턴스를 단일 구문 내에서 생성할 수 있으며, 강한 순환 참조도 만들어내지 않습니다. 그리고 capitalCity 프로퍼티에 바로 접근할 수 있으며, 옵셔널 값을 언래핑하기 위한 느낌표 마크를 사용할 필요도 없는 것이죠.

 

In the example above, the use of an implicitly unwrapped optional means that all of the two-phase class initializer requirements are satisfied. The capitalCity property can be used and accessed like a non-optional value once initialization is complete, while still avoiding a strong reference cycle.

 

위의 예시에서, 암시적 언래핑된 옵셔널의 사용은 모든 두 단계(two-phase) 클래스 이니셜라이저의 요구사항을 만족하는 것을 의미합니다. capitalCity 프로퍼티는 사용될 수 있고 일단 초기화가 끝나면 강한 순환 참조를 피하면서 옵셔널이 아닌 값과 같이 엑세스 할 수도 있어요. 

 

 

다음 시간에는 '클로저에서 강한 순환 참조(Strong Reference Cycles for Closures)'에 대해 알아보겠습니다.

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함