Swift) Notifications

Notifications란?

정보를 브로드캐스팅하고, 브로드캐스트를 구독하기 위한 디자인 패턴입니다. 즉 일대다수의 이벤트를 전달 할 때 유용하게 사용 할 수 있습니다. 

Notifications의 구성

  • Notification : NotificationCenter에 등록된 관찰자들에게 브로드캐스트되는 정보를 위한 컨테이너
  • NotificationCenter : 관찰자를 등록, 알림을 송신하는 매커니즘
  • NotificationQueue: 알람을 등록, 자신이 원할때 알람을 송신해줄 수 있도록 해주는 알림 버퍼

NotificationCenter 매커니즘

NotificationCenter을 통해 특정 알람을 받을 Observer를 추가 하고, Post를 통해 해당 Observer에 알람을 보낼 수 있습니다.

 

우측에 있는 ViewController의 버튼을 누르면 좌측에 있는 ViewController에 원하는 프린트를 출력하도록 구성해보도록 하겠습니다.

우선은 Notification을 받기 위해 NotificationCenter에 Observer를 추가하고, 해당 Notification을 받으면 수행할 function을 설정합니다.

addObserver는 "Call"이라는 이름의 Notification이 오면, observerCall() 함수를 실행시킨다는 뜻으로 이해하면 편합니다.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(observerCall), name: Notification.Name("Call"), object: nil)
    }

    @objc func observerCall() {
        print("Call viewcontroller")
    }

}

 

 

그 다음 버튼을 누르면 Notification을 Post 할 수 있도록 합니다. 이 역시 NotificationCenter을 이용하여 Post합니다.

class ViewControllerTwo: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    @IBAction func buttonTap(_ sender: Any) {
        NotificationCenter.default.post(name: Notification.Name("Call"), object: nil)
    }

}

이제 버튼을 누르면 프린트 되는것을 확인 할 수 있습니다.