[iOS] Delegation

Eugenie·2022년 7월 4일
0

Delegation

Delegate: n. 대표(자), 사절, 위임, 대리(자)
		  v. (권한, 업무 등을) 위임하다, (대표를) 선정하다

Delegation Design Pattern

델리게이션 디자인 패턴은
하나의 객체가 다른 객체를 대신해 동작 또는 조정할 수 있는 기능을 제공한다.

🎾 Foundation, UIKit, AppKit, Cocoa Touch 등 애플의 프레임워크에서 광범위하게 활용
🎾 주로 프레임워크 객체가 위임을 요청, 커스텀 컨트롤러 객체가 위임을 받아 특정한 이벤트에 대한 기능을 구현
🎾 커스텀 컨트롤러 내에서 세부 동작을 구현하므로써 동일한 동작에 대해 다양한 대응 가능

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의 차이?

profile
🌱 iOS developer

0개의 댓글