[예제] NotificationCenter

J.Noma·2021년 11월 2일
0
// 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를 적는게 자연스러움
        notificationCenter.post(name: notiName, object: nil)
    }
}
profile
노션으로 이사갑니다 https://tungsten-run-778.notion.site/Study-Archive-98e51c3793684d428070695d5722d1fe

0개의 댓글