Delegation
Delegate: n. 대표(자), 사절, 위임, 대리(자)
v. (권한, 업무 등을) 위임하다, (대표를) 선정하다
Delegation Design Pattern
델리게이션 디자인 패턴은
하나의 객체가 다른 객체를 대신해 동작 또는 조정할 수 있는 기능을 제공한다.
DataSource
데이터소스는
데이터를 제어하는 기능을 위임받는다.
// Datasource example
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell
// return a cell ie UITableViewCell
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
// return a number ie an Int
func tableView(tableView: UITableView,
titleForHeaderInSection section: Int) -> String?
// return the title ie a String
❓ DataSource vs. Delegate
데이터소스는 데이터를 받아 뷰를 그려주는 역할을 한다고 생각하면 된다.
델리게이트는 어떤 행동에 대한 동작을 제시한다.
데이터소스는 보여주는 것을 담당했다면
델리게이트는 사용자에게 보여지는 부분 중 어떤 것을 클릭하거나
어떤 행동을 했을 때, 그 행동에 대한 동작을 수행하게 된다.
// Delegate example
func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: IndexPath)
func tableView(tableView: UITableView,
willBeginEditingRowAtIndexPath indexPath: IndexPath)
func tableView(tableView: UITableView,
willBeginEditingRowAtIndexPath indexPath: IndexPath)
Protocol
코코아터치에서 프로토콜을 사용해 델리게이션과 데이터소스를 구현할 수 있다.
📚 Reference
boostcourse - iOS 앱 프로그래밍
iOS ) DataSource와 Delegate의 차이?