Notification Center

도윤·2022년 1월 8일
0

Notificaton Center란 등록된 event가 발생하면 등록된 observer에 정보를 알리는 역할을 한다

Default

앱에서 발생한 Notifications들이 default notification center로 전달된다. 따로 notifications들을 만들지 않는다면 Notification.default로 사용하면 된다.

따로 내 소유의 notification center를 만들어 알림을 전송할 수도 있다.
notification이 notification 센터로 전송되면, notification center는 등록된 observers list들을 관찰하는데 이 과정에서 앱의 속도가 늦어질 가능성이 있다.

하나 이상의 notification center를 기능적으로 만들면, notification이 전송될 때 더 적은 시간이 걸릴 수 있고, 앱의 성능을 향상시킬 수 있다.

Observers 등록

NotificationCenter.default.addObserver(_ observer: Any, 
        selector aSelector: Selector, 
            name aName: NSNotification.Name?, 
          object anObject: Any?)

default Notification center의 observer list에 등록하는 메서드이다.

Notification.default: 클래스 내에서 전역으로 만들 수 있는 알림 변수로, 따로 Notification center를 작성하지 않는 경우 사용하면 된다.

observer: 등록할 object
Selector: 알림이 발생할 경우, 실행할 함수를 @objc 형태로 작성.
name: Notification의 key로 unique해야하며, 알림을 식별하는 태그이다.
Object: 발송자가 오브젝트에 보내려하는 객체. 어떠한 형태로 전달 할 수 있다.(Bool,string,Dictionary,Array,Int,Nil)

Post

Name의 Notification들에게 Notification을 시작하도록 명령하는 것과 유사.

NotificationCenter.default.post(name aName: NSNotification.Name, 
   object anObject: Any?)

name: notification의 이름
object: notification에게 전달할 객체

Notification메소드를 통해 데이터를 어떻게 주고 받을까?

step1 : @objc

observer를 등록할 때 사용할 @ojbc 함수 작성.

@objc func selector(_ :){
	//code
//

step2 : Receiver(Register you NotificationCenter Observer)

NotificationCenter.default.addObserver(_ observer: Any, 
        selector aSelector: Selector, 
            name aName: NSNotification.Name?, 
          object anObject: Any?)

step3: Post Notification

NotificationCenter.default.post(name aName: NSNotification.Name, 
   object anObject: Any?)

Remove Notification

NotificatioCenter에 등록된 Observer를 삭제할 필요가 있을 때 실행.

func removeObserver(_ observer: Any, 
               name aName: NSNotification.Name?, 
             object anObject: Any?)

언제 Notification 센터를 사용?

  • 앱 내에서 공식적인 연결이 없는 두 개 이상의 컴포넌트들이 상호작용이 필요할 때
  • 상호작용이 반복적으로 그리고 지속적으로 이루어져야 할 때
  • 일대다 또는 다대다 통신을 사용하는 경우

출처 : https://developer.apple.com/documentation/foundation/notificationcenter
https://medium.com/@nimjea/notificationcenter-in-swift-104b31f59772

       

0개의 댓글