NotificationCenter 첫 사용기

·2020년 8월 25일
1

들어가기 전에..

NotificationCenter 클래스의 기본 of 기본적인 기능만 사용해 보았습니다.

NotificationCenter가 대체 뭐하는 자식이지???? 이해하고 싶으신 분들에게만 추천합니다.. (ㅠㅠ)

노티피케이션 센터랑 첫만남 후 자기소개만 주고받은 수준임 넵




NotificationCenter ?

NotificationCenter는 등록된 객체들에게 동시에 Notification을 전달해주는 클래스이다.

즉, 한 객체가 여러 객체들에게 동시에 어떤 내용을 전달하고 싶을 때 사용할 수 있다.


그렇다면 Notification은 뭔데?

Notification

노티피케이션 센터에 등록된 옵저버들에게 broadcast될 정보를 담고 있는 구조체이다.

init(name: Notification.Name, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil)
  • name : Notification의 이름
  • object : post할 대상이 옵저버들에게 보내고자 하는 객체
  • userInfo : 노티피케이션과 관련된 값 또는 객체의 저장소

예를 들어 네트워킹을 이용하는 앱에서 네트워킹이 시작될 때 notification을 보낸다고 해보자.

이 때, 네트워킹 시작 시점에 관한 정보를 함께 넘겨줄 수 있다.




다시 NotificationCenter로 돌아와..

주요 메소드

post(_ notification: Notification)

→ 해당하는 노티피케이션을 노티피케이션 센터에 post한다.

func post(_ notification: Notification)
  • notification : 발송하고자 하는 notification

addObserver(_:selector:name:object:)

→ 노티피케이션 센터에 옵저버를 등록한다.

func addObserver(_ observer: Any, 
        selector aSelector: Selector, 
            name aName: NSNotification.Name?, 
          object anObject: Any?)
  • observer : observer로 등록할 객체

  • aselector

    : selector 개념이 아직 잘 잡히지 않았다 ..

    일단 notification을 받았을 때 실행할 동작으로 사용?했다. #selector(메소드) 이렇게.

  • aName : 받고자 하는 notification의 이름

  • anObject : (추후 추가하겠음..)


removeObserver(_:name:object:)

→ 해당 노티피케이션을 가리키는 옵저버 중, 인자로 들어온 옵저버를 제거한다.

func removeObserver(_ observer: Any, 
               name aName: NSNotification.Name?, 
             object anObject: Any?)
  • observer : 제거하고자 하는 observer
  • aName : notification의 이름
  • anObject : ..



예제

카페에 한 명의 캐셔여러 명의 바리스타들이 있다고 가정해보자.

주문이 들어왔을 때, 캐셔는 주문 목록에 주문을 추가하고 바리스타들에게 주문 목록 확인하세요!!! 라고 알리고자 한다.


캐셔는 주문 목록 확인하쇼!!! 라고 노티를 보낼 것이다. (같이 보낼 객체 이런 거 없음. 소리만 지를 것임.)

일단 이 Notification 이름을 정의해두자.

extension Notification.Name {
    static let checkOrders = Notification.Name("checkOrders")
}

바리스타들은 알림이 언제 올 지 관찰하고 있어야겠지요? → Observing

NotificationCenter.default.addObserver(self, selector: #selector(checkOrder), name: .checkOrders, object: nil)
  • 등록하고자 하는 observer : 바리스타 자기 자신 → self
  • 해당 notification을 받았을 때 실행하고자 하는 작업 → checkOrder (따로 함수를 만들어 두었음)
  • 받고자 하는 notification 이름 : .checkOrders

Notification도 정의했고, observer 등록도 했으니 이제 Notification을 보내자. → post

NotificationCenter.default.post(name: .checkOrders, object: nil)

이렇게 캐셔 객체에서 post를 하면 동시에 옵저버들에게(여기서는 바리스타겠죠?) 노티피케이션이 전달된다.

그러면 각 바리스타 객체들의 checkOrder 메소드가 호출될 것이다.


끝!

profile
이사중.. (티톨버림..)

0개의 댓글