- Notification
- 장점
- 많은 줄의 코드가 필요없어 쉽게 구현가능
- 다수의 객체들에게 동시에 이벤트의 발생을 알려줄 수 있다.
- Notification과 관련된 정보를 Any? 타입의 object, [AnyHashable:Any]? 타입의 userInfo로 전달할 수 있다.
- NotificationCenter를 통해 정보를 저장하기 위한 구조체는 name, object, userInfo로 구성되어있다. 옵저버에게 전달되는 구조체로 정보가 담겨있고, 해당 알림을 등록한 옵저버에게만 전달된다.
var name: Notification.Name var object: Any? userInfo: [AnyHashable: Any]?
- name: 전달하고자하는 notification의 이름으로 이걸 통해 알림을 식별한다.
- object: 발송자가 옵저버에게 보내려고 하는 객체, 주로 발송자 객체를 전달하는 데 쓰임
- userInfo: notification과 관련된 값 또는 객체의 저장소로 Extra data를 보내는데 사용가능하다.
- 장점
- NotificationCenter(NSNotificationCenter)
- notification이 오면 observer pattern을 통해서 옵저버들에게 noticication을 전달하기 위해 사용하는 클래스이다. notification을 발송하면 NotificationCenter에서 메세지를 전달한 observer를 처리할 때까지 대기한다.
- 흐름이 동기적으로 흘러간다.
- Notification Center를 통해서 앱의 한 파트에서 다른 파트로 데이터를 전달할 수 있다.
- Notification이 오면 등록된 옵저버 리스트를 스캔한다.
- Notification Center는 어플리케이션 어느 곳에서 어느 객체와도 상호작용을 할 수 있다.
- 상호작용을 하기 전에 extension으로 Notification.Name을 추가해주면 편리하다.
extension Notification.Name {
static let secret = Notification.Name("shh")
}
- NotificationCenter로 발송하기(Post)
- Name의 해당자들에게 일을 수행하라고 시킨다.
NotificationCenter.default.post(name : .secret, object: nil, userInfo: [NotificationKey.password: "암호는 !@#$"])
- Notification Center에 Observer등록하기
- notification을 observe해주기 전에 Notification Center에 addObserver 과정을 무조건 먼저 거쳐줘야 원하는 신호를 관찰 가능하다
- removeObserver도 방식은 같다.
NotificationCenter.default.addObserver(self, selector: #selector(answerToMaster(notification:)), name: .secret, object: nil) @objc func answerToMaster(notification: Notification) { guard let key = notification.userInfo?[NotificationKey.password] as? String else { return } print("\\(name): \\(key)") }
- NotificationCenter 사용하면 좋을 때
- 앱 내에서 공식적인 연결이 없는 두 개 이상의 컴포넌트들이 상호작용이 필요할 때
- 상호작용이 반복적으로 그리고 지속적으로 이루어져야 할 때
- 일대다 또는 다대다 통신을 사용하는 경우
728x90
'개발일기 > IOS' 카테고리의 다른 글
[Swift] - Lottie 애니메이션 실습 삽질정리(feat. sandbox) (0) | 2024.03.15 |
---|---|
[IOS] - 기초 공부 (0) | 2024.03.15 |
[Swift] - UIGestureRecognizer (0) | 2024.03.15 |
[Swift] - View의 Cycle (0) | 2024.03.15 |
[Swift] - Animation 정리 2 (0) | 2024.03.15 |