본문 바로가기

iOS

NotificationCenter

NotificationCenter

직역하면 알림센터로, Observer에게 Notification 객체를 전달하는 싱글톤 객체입니다.

델리게이트 패턴은 일대일 송수신에 장점이 있지만, 이 객체는 일대다, 다대다 통신의 장점을 갖고 있습니다.

 

Notification

    /// A tag identifying the notification.
    public var name: Notification.Name

    /// An object that the poster wishes to send to observers.
    ///
    /// Typically this is the object that posted the notification.
    public var object: Any?

    /// Storage for values or objects related to this notification.
    public var userInfo: [AnyHashable : Any]?

Notification에는 name, object, userInfo가 담겨져 있습니다.

name: 전달하고자 하는 Notification 식별 이름

object: 전달하는 데이터(객체)

userInfo: Notification과 관련된 데이터

 

Post(발송하기)

NotificationCenter.default.post(name: NSNotification.Name, object: Any?, userInfo: [AnyHashable : Any]?)

이벤트 발생 지점에서 NotificationCenter의 post를 통해 Notification을 전송합니다.

전송할때 식별되는 이름은 Notification.Name 입니다.

 

 

전달받기(Observer 등록)

NotificationCenter.default.addObserver(forName: NSNotification.Name?, object: Any?, queue: OperationQueue?, using: (Notification) -> Void)

알림을 받을 지점에서 Observer를 등록합니다.

알림받고 using: 클로저를 통해 바로 실행시키거나 알림을 받으면 메서드가 실행되도록 설정할 수 있습니다.

NotificationCenter.default.addObserver(Any, selector: Selector, name: NSNotification.Name, object: Any?)

 

'iOS' 카테고리의 다른 글

UICollectionViewLayout과 UICollectionViewFlowLayout  (0) 2025.03.03
UIBeizerPath  (0) 2025.02.26
iOS Combine  (0) 2025.02.19
URLSession 번역  (0) 2024.12.13
Fetching website data into memory  (0) 2024.12.10