iOS/App

Delegate: AnyObject

소토리텔러 2023. 12. 23. 02:12

 

왼쪽이 MainViewController, 오른쪽이 SettingViewController

 

 

Delegate를 사용해서 ViewController 간의 데이터를 전달하는 것을 연습했다.

강의에서 Delegate를 AnyObject를 상속받아서 클래스화 시켰는데 이유를 모르겠어서 찾아봤다.

 

MainViewController
SettingViewController

 

 

SettingViewController는 SettingDelegate를 채택하는 무언가가 필요하다.

이 앱에서는 MainViewController가 SettingDelegate를 채택하고 있다.

따라서 MainViewController는 SettingViewController를 참조하고

SettingViewController는 MainViewController를 참조하게 된다.

 

위와 같이 서로를 참조하게 되는 경우 순환참조가 발생할 수 있으니

이를 방지하기 위해 delegate를 weak로 선언해주고 싶다.

 

그래서 delegate 변수에 weak를 붙여주었더니

'weak' must not be applied to non-class0bound

 

 

'weak'는 class 타입에만 붙일 수 있으니 SettingDelegate를 클래스화 시켜야 된다고 한다.

그래서 AnyObject를 상속받게 함으로써 클래스화 시켰더니 오류도 사라졌다.

SettingDelegate: AnyObject