Design Pattern

Delegate Pattern

motosw3600 2021. 12. 14. 13:25

Delegate

  • Delegate(대리자, 위임자)
  • 어떠한 객체가 다른객체에게 책임을 위임하는 것
  • iOS에선 보통 protocol을 사용하여 해당 객체의 일을 protocol을 채택하여 대신 수행한다.(순환참조 주의!)
  • 객체간에 직접 참조해서 작업을 하는것 보다 delegate 패턴을 통해 객체간의 의존성과 책임을 줄일 수 있다.

TextFieldDelegate 예시

TextField와 Label을 추가해 준뒤

 

 

 

ViewController에서 UITextFieldDelegate를 채택

viewDidLoad안에 textField.delegate.self(이부분이 TextField의 일을 위임하겠다는 뜻)

 

 

채택한 UITextFieldDelegate의 func중 textFieldShouldReturn함수를 정의

 

 

실행 결과

 

 

 


weak를 사용한 retain방지

하나의 클래스를 서로다른 인스턴스를 만들고 서로의 인스턴스의 delgate를 참조하면 retain cycle이 발생할 수 있다.

TableView와 Cell의 관계를 예를들면 TableView를 TableViewController cell을 CellViewController라고 할 때 TableViewController는 Cell의 정보를 얻기위해 인스턴스를 만들고 delegate를 설정한다.

 

protocol CellViewControllerProtocol {
  func cellCount()
}

class TableViewController: UIViewController, CellViewControllerProtocol {
   let cellViewController = CellViewController()
   cellViewController.delegate = self
}

class CellViewController: UIViewController {
   var delegate: CellViewControllerProtocol?
}

 

위방식에서 TableViewController가 dismiss되거나 메모리에서 해제될 때 CellViewController의 delegate의 참조가 남아있어 retain Cycle로인한 memory leak이 발생한다.

따라서 delegate를 weak으로 선언하여 retain을 방지

 

protocol CellViewControllerProtocol: AnyObject {
  func cellCount()
}

class TableViewController: UIViewController, CellViewControllerProtocol {
   let cellViewController = CellViewController()
   cellViewController.delegate = self
}

class CellViewController: UIViewController {
   weak var delegate: CellViewControllerProtocol?
}

 

'Design Pattern' 카테고리의 다른 글

DI(Dependency Injection)  (0) 2022.01.19
Clean Architecture  (0) 2021.12.10
MVC Pattern  (0) 2021.12.10