[iOS] Delegate 와 Notification 의 차이

a-paka·2022년 3월 22일
0

Delegate 와 Notification 는 클래스 간에 커플링이나 디펜던시를 최대한 줄일 수 있게 도와주기 위해 고안되었다. Delegate (대리) 는 단어 뜻 그대로, 다른 객체에게 메세지를 보냈을 때 알아서 처리해달라고 요청하는 것이다.

TableView 가 스크롤을 했을 때, 추가적인 동작을 위해 Delegate 에게 메시지를 전달하는 것이 그 예시이다.

TableView 가 행을 선택하기 전, Delegate 에게 선택이 가능한지 물어볼 수도 있다.

Delegate 는 프로토콜 기반으로 동작하는데, 이는 클래스 간의 디펜던시를 최소화 할 수 있고, 프로토콜을 선언하는 입장에서 꼭 구현해야 하는 / 구현하지 않아도 되는 메소드를 분리할 수 있다.

ref: https://useyourloaf.com/blog/delegation-or-notification/

Notification 은 메시지를 브로드캐스팅한다. 앞의 예시에서 Delegate 는 sender 와 상호작용이 가능하다고 했는데, Notification 의 receiver 는 sender 에게 어떤 동작을 하도록 작용할 수 없다.

NotificationCenter 가 방송국 역할을 한다고 할 수 있다.
(addObserver 로 옵저버 등록, post 로 메시지 전송)


The concept of Delegate and Notification is devised in order to reduce couplings and dependencies (most of them are unnecessary.) between classes in application.

Delegate is, literally assigned to be delegated any actions to be done whenever sender sends certain messages.

For example, when scrolling table view, send a message to delegate to handle further actions.

Or before selecting a row, sender can ask its delegate whether to be allowed or not.

Delegate pattern is protocol based, it minimizes dependencies between classes, and separator must/optionally implemented methods easily.

In the meantime, Notification does broadcast messages. As in the previous example, Delegate can interact with its sender. But the receiver of Notification cannot force its sender to perform any action.

NotificationCenter plays a role as broadcast center, as receivers can add observers and senders post messages via NotificationCenter.

profile
iOS Engineer

0개의 댓글