Notification Center

J.Noma·2021년 10월 23일
0

iOS : Foundation 모음

목록 보기
1/3

이번 포스팅에서는 인스턴스 간 소통 방법 중 하나인 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)
    }
}

🐶 장.단점

👍 장점

  • 가장 큰 장점은 객체 간 서로의 존재를 몰라도 된다는 점
    (addObserverpost메서드의 object argument를 사용하려면 알아야되긴 함)

  • 여러 객체에게 한 방에 뿌릴 수 있다 (filtered Broadcast 방식이므로)

👎 단점

  • 코드가 분산되어 디버깅이 어려워질 수 있다
profile
노션으로 이사갑니다 https://tungsten-run-778.notion.site/Study-Archive-98e51c3793684d428070695d5722d1fe

0개의 댓글