이 글에서는 델리게이트(delegate)가 무엇인지, 그리고 직접 만드는 방법까지 단계별로 알아봅니다. 먼저 기본 개념부터 살펴보겠습니다.
델리게이트(Delegate)란?
델리게이트는 객체 간의 통신을 가리키는 간단한 용어입니다. 여러 객체를 서로 연결하고, 한 객체에서 발생한 일을 다른 객체에 전달할 수 있도록 해주는 손쉬운 방법입니다.
델리게이트는 어떻게 작동할까요?
델리게이트는 프로토콜(protocol)을 통해 구현됩니다. 프로토콜은 이벤트가 발생하는 클래스 안에서 선언되며, 그 이벤트가 발생했을 때 다른 클래스에 알려야 할 필요가 있을 때 사용됩니다. 프로토콜에는 함수의 선언만 작성하고, 실제 함수 본문은 이벤트를 받는 쪽 클래스에서 정의합니다.
델리게이트 만들기
간단한 예제 프로젝트를 통해 단계별로 살펴보겠습니다.
수행해야 할 단계는 다음과 같습니다.
FirstViewController라는 이름의 클래스와 SecondViewController라는 이름의 클래스를 각각 생성하고, 스토리보드(storyboard)에서 두 클래스에 대응하는 뷰 컨트롤러를 만듭니다.
SecondViewController에 프로토콜을 선언합니다. 프로토콜은 반드시 클래스나 다른 객체 외부에 선언해야 합니다.
protocol SecondViewControllerDelegate {
func buttonPressedInVC2()
}
SecondViewController 안에서 방금 만든 델리게이트의 옵셔널(optional) 객체를 생성합니다.
var delegate: SecondViewControllerDelegate?
SecondViewController에서 특정 이벤트가 발생할 때 프로토콜에 선언된 함수를 호출해야 합니다. 여기서는 두 번째 뷰 컨트롤러에서 버튼이 눌렸을 때 발생하는 이벤트를 만들어 보겠습니다.
@IBAction func buttonTapped(_ sender: UIButton) {
self.delegate?.buttonPressedInVC2()
self.navigationController?.popViewController(animated: true)
}
여기까지가 SecondViewController에서 필요한 작업입니다. 이제 FirstViewController 차례입니다.
FirstViewController가 SecondViewControllerDelegate 프로토콜을 채택(conform)하도록 만듭니다. 프로토콜을 채택하면 Xcode가 자동으로 프로토콜 스텁(protocol stubs)을 추가하라고 안내해 줍니다.
extension FirstViewController: SecondViewControllerDelegate {
func buttonPressedInVC2() { }
}
방금 구현한 프로토콜 메서드 안에는, 델리게이트 액션이 발생했을 때 실행하고 싶은 코드를 작성합니다.
예를 들어 FirstViewController에 레이블(label)을 하나 만들고, 델리게이트 메서드가 호출될 때 그 텍스트를 변경해 보겠습니다.
extension FirstViewController: SecondViewControllerDelegate {
func buttonPressedInVC2() {
self.lblOne.text = "Delegate Implemented"
}
}
마지막 단계가 남았습니다. SecondViewController의 delegate 객체는 옵셔널이므로 값을 할당하기 전까지는 nil입니다. 따라서 FirstViewController에서 SecondViewController로 화면을 전환할 때 이 객체에 자기 자신(self)을 할당해야 합니다.
이를 위해 FirstViewController에 버튼을 하나 만들겠습니다.
@IBAction func goToNextVC(_ sender: Any) {
let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondViewController") as! SecondViewController
vc.delegate = self
self.navigationController?.pushViewController(vc, animated: true)
}
그리고 아직 눈치채지 못했다면, FirstViewController를 네비게이션 컨트롤러(Navigation Controller) 안에 임베드(embed)해야 합니다. 이제 앱을 실행하고 결과를 확인해 보세요.
