NotificationCenter
A notification dispatch mechanism that enables the broadcast of information to registered observers.
⇒ 등록된 Observer에게 정보를 BroadCast하는 것을 가능하게 하는 Notification Dispatch(보내기) 메커니즘이다.
세 가지의 관계
- 알림을 만들어내는
Publisher
- 알림을 전달하는 Dispatcher 역할의
NotificationCenter
- 알림을 관찰하는
Observer
기본 예제 코드
- NotificationCenter을 하나 생성 → Notification.Name을 통하여 이름을 맞춘다.
NotificationCenter.default.post(name: NSNotification.Name("Notification"), object: nil, userInfo: nil)
- Observer 생성하기
NotificationCenter.default.addObserver(self, selector: #selector(didRecieveNotification(_:)), name: NSNotification.Name("Notification"), object: nil)
@objc func didRecieveNotification(_ notification: Notification) {
print("Notification")
}
Post의 Object로 값 전달하기
- NotificationCenter 생성하기
NotificationCenter.default.post(name: NSNotification.Name("Notification"), object: "Object")
- 아래와 같이 addObserver에서 object 가져오기
NotificationCenter.default.addObserver(self, selector: #selector(didRecieveNotification(_:)), name: NSNotification.Name("Notification"), object: nil)
@objc func didRecieveNotification(_ notification: Notification) {
let value = notification.object as! String
print(value)
}
UserInfo로 값 전달하기
- NotificationCenter 생성하기
NotificationCenter.default.post(name: NSNotification.Name("Notification"), object: nil, userInfo: ["MIRO": "Password"])
- Observer 등록해주기
NotificationCenter.default.addObserver(self, selector: #selector(didRecieveNotification(_:)), name: NSNotification.Name("Notification"), object: nil)
@objc func didRecieveNotification(_ notification: Notification) {
guard let value = notification.userInfo?["MIRO"] as? String else {
return
}
print(value)
}
공식문서
Each running app has a default notification center, and you can create new notification centers to organize communications in particular contexts.
→ default 말고도 만약 새로운 notification center를 생성하고 싶다면 만들수 있다!
If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:)
to create your observer, you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it.
→ 만약 addObserver(_:selector:name:object:)
메소드를 사용하고, app target이 9.0 이상이면 굳이 removeObserver를 할 필요가 없다.
'iOS' 카테고리의 다른 글
[iOS] Diffabledatasource의 identifier는 왜 Hashable 해야 할까? (0) | 2023.06.08 |
---|---|
[iOS] FileManager (0) | 2023.06.08 |
[iOS] Gesture recognizer, Touch event handling (0) | 2023.02.28 |
[iOS] 의존성 관리 도구(Package Manager) (0) | 2023.02.21 |
[iOS] TableView에서 Swipe해서 Delete하기 (0) | 2023.02.09 |