[iOS]NotificationCenter
Swift 초보의 코드이므로, 참고만 해주시면 감사합니다 😅

NotificationCenter 📑

정의 ▾

Notification Center

Apple Developer

  • 그대로 번역하면 "등록된 관찰자에게 정보를 브로드캐스트 할 수 있도록 하는 알림 디스패치 메커니즘"이라고 합니다.
  • 쉽게 말해 Notification이 오면 Observer Pattern(옵저버 패턴)을 통해서 등록된 옵저버들에게 Notification을 전달하기 위해 사용하는 클래스라고 보면 됩니다.
  • 우리는 Notification도 들어봤을 텐데, Notification과 NotificationCenter 무슨 차이가 있는지는 아래 Notification에 대한 정의를 볼게요.

 

Notification

Apple Developer

  • 그대로 번역하면 "등록된 모든 관찰자에게 알림 센터를 통해 방송되는 정보용 컨테이너"라고 합니다.
  • 쉽게 말해, Notification은 NotificationCenter를 통해 정보를 저장하기 위한 구조체입니다.
  • 옵저버들에게 전달되는 구조체로 정보가 담겨있고, 해당 알림을 등록한 옵저버에게만 전달됩니다.
  • 구성 ▾
    • name: 전달하고자 하는 Notification의 이름(식별자 역할)
    • object: 발신자가 옵저버에게 보내려고 하는 객체
    • userInfo: Notification과 관련된 값 또는 객체의 저장소(Extra data를 보내는 데 사용이 가능하다고 함)

 

언제 사용하는게 적합할까 ?

  • 앱 내에서 연결이 없는 두 개 이상의 컴포넌트들이 상호작용을 해야 할 때
  • 위에 상호작용이 반복적/지속적으로 진행되어야 할 때
  • 일대다 || 다대다 통신을 사용하는 경우

 

어떻게 사용할까?

Post ▾

  • 이벤트 처리를 해줄 곳에 작성을 해줍니다.
NotificationCenter.default.post(name: Notification.Name("handleSomethingEvent"), object: nil)

 

Add Observer ▾

  • 이벤트가 일어날 곳에 작성을 해줍니다.
NotificationCenter.default.addObserver(self, selector: #selector(moveController(_:)),
				name: Notification.Name("handleSomethingEvent"), object: nil)

 

Remove Observer ▾

  • 해당 옵저버를 삭제해줍니다.
  • 저는 주로 옵저버 등록을 해주는 곳에 View가 사라지면 해당 옵저버를 삭제시켜, 불필요한 메모리 낭비 요소를 제거했습니다.
NotificationCenter.default.removeObserver(self, name: NSNotification.Name("handleSomethingEvent"), object: nil)

 

 

Example 📓

상황 설명 ▾

  • 두 개의 클래스가 있고, 각각의 클래스 이름은 testFirsttestSecond입니다.
  • testFirst 클래스에는 버튼이 있고, 이 버튼을 클릭 시, testSecond의 배경 색이 변하게 하고 싶은 상황입니다.
  • 다른 메서드는 제쳐두고 Notification만 집중해봅시다.
class testFirst {
    @IBAction func buttonTapped() {
    	NotificationCenter.default.post(name: Notification.Name("changeBackgroundColor"),
        				object: nil)
    }
}
  • 버튼을 클릭 시 해당 옵저버는 changeBackgroundColor이라는 이름을 가진 옵저버에게 신호를 보냅니다.

 

class testSecond {
   override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
      NotificationCenter.default.addObserver(self, selector: #selector(handleBackgroundColor(_:), name: Notification.Name("changeBackgroundColor"), object: nil)
	}
    
    @objc func handleBackgroundColor(_ noti: Notification) {
    	view.backgroundColor = .systemTeal
    }
}
  • testSecond 클래스에서 옵저버를 등록해주고, 해당 옵저버에 신호가 올 때, handleBackgroundColor이라는 메서드를 실행시켜 뷰의 배경색을 바꿔줍니다.

 

override func viewWillDisappear(_ animated: Bool) {
   super.viewWillDisappear(animated)

   NotificationCenter.default.removeObserver(self, 
    			name: Notification.Name("changeBackgroundColor"), object: nil)
}
  • View가 사라질 때, 해당 옵저버를 제거해줌으로써 메모리를 절약할 수 있습니다.

'iOS_Swift.zip' 카테고리의 다른 글

[iOS]Strong과 weak 참조 방식  (0) 2022.02.27
[iOS]Protocol  (0) 2022.02.20
[iOS]App Thinning  (0) 2022.02.16
[iOS]lazy 키워드  (0) 2022.02.16
[iOS]Frame과 Bounds의 차이  (0) 2022.02.14