이번 포스팅에서는 인스턴스 간 소통 방법 중 하나인 Notification Center에 대해 사용법 위주로만 정리하고 장.단점에 대해 간단하게 다룹니다
// 1. NotificationCenter 인스턴스 가져오기 (싱글턴)
let notificationCenter: NotificationCenter = NotificationCenter.default
// 2. Notification 이름 인스턴스 생성 (nested type인듯)
let notiName: Notification.Name = Notification.Name("noti날리자")
struct Receiver {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
// 3. Observer 등록
// - _ : observer등록할 객체
// - selector : noti를 받으면 수행할 메서드
// - name : 선별용. 수신할 noti의 name
// - object : 선별용. noti를 보낸 객체
notificationCenter.addObserver(self, selector: #selector(receivedNotification), name: notiName, object: nil)
}
// 4. selector 구현
@objc func receivedNotification() {
print("I got a notification")
}
}
struct Sender {
func send() {
// 5. notification 발송
// - name : 선별용. 어떤 이름으로 noti를 보낼 것인지
// - object : 선별용. noti를 누가 보냈는지 기입. 보통 self를 적는게 자연스러움
notification.post(name: notiName, object: nil)
}
}
가장 큰 장점은 객체 간 서로의 존재를 몰라도 된다는 점
(addObserver
나 post
메서드의 object
argument를 사용하려면 알아야되긴 함)
여러 객체에게 한 방에 뿌릴 수 있다 (filtered Broadcast 방식이므로)