NotificationCenter란
NotificationCenter란
객체 간의 이벤트를 전달하는 시스템
기능
- 객체 간의 직접적인 연결 없이 이벤트 전달 가능
- 뷰 컨트롤러 간 데이터나 이벤트 전달 가능
- 비동기적으로 실행 가능하여 UI업데이트에 활용 가능
기본 개념
- post() - 이벤트 발생
- 특정 이벤트가 발생하면 알림을 보내 다른 객체에 전달함
1 2
NotificationCenter.default.post(name: Notification.Name("CustomEvent"), object: nil)
- addObserver() - 이벤트 감지
- 이벤트 발생시 감지하고 특정 동작 수행
1 2 3 4 5 6
NotificationCenter.default.addObserver(self, selector: #selector(handleCustomEvent), name: Notification.Name("CustomEvent"), object: nil) @objc func handleCustomEvent() { print("📢 CustomEvent 발생!") }
- removeIbserver() - 이벤트 제거
- 뷰 컨트롤러가 해제될 때 옵저버를 제거
1 2 3 4
deinit { NotificationCenter.default.removeObserver(self, name: Notification.Name("CustomEvent"), object: nil) }
This post is licensed under CC BY 4.0 by the author.