2023. 8. 22. 11:27ㆍiOS
노티피케이션이란??
Notification이 오면 observer pattern을 통해서 등록된 옵저버들에게 Notification을 전달하기 위해 사용하는 클래스. Notification을 발송하면 NotificationCenter에서 메세지를 전달한 observer를 처리할 때까지 대기한다.
- 즉, 흐름이 동기적으로 흘러간다.
- Notification Center를 통해서 앱의 한 파트에서 다른 파트로 데이터를 전달할 수 있다.
- Notification이 오면 등록된 observer list를 스캔한다.
- Notification Center는 어플리케이션 어느 곳에서 어느 객체와도 상호작용을 할 수 있다.
NotificationCenter는 언제 사용해야할까?
- 앱 내에서 공식적인 연결이 없는 두 개 이상의 컴포넌트들이 상호작용이 필요할 때
- 상호작용이 반복적으로 그리고 지속적으로 이루어져야 할 때
- 일대다 또는 다대다 통신을 사용하는 경우
- 먼저 노티를 던져주기 위해서 `NotificationCenter.default.post`라는 메서드를 활용합니다.
func postName() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "1"), object: self.nameLabel.text)
}
func postNumber() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "2"), object: self.phoneNumberLabel.text)
}
@IBAction func pushView(_ sender: UIButton) {
let secondView = SecondViewController()
self.navigationController?.present(secondView, animated: true)
postName()
postNumber()
}
- 노티를 던져줘야한다 버튼을 누르면서 화면 이동을 진행할때에 노티를 던져 줘야지만 넘어가게 된다.
두번째 화면
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
addObserverName()
addObserverNumber()
}
func addObserverName() {
NotificationCenter.default.addObserver(forName: Notification.Name("1"), object: nil, queue: nil) { [weak self] notification in
if let test = notification.object as? String {
self?.titleLabel.text = test
}
}
}
func addObserverNumber() {
NotificationCenter.default.addObserver(forName: Notification.Name("2"), object: nil, queue: nil) { [weak self] notification in
if let test = notification.object as? String {
self?.subTitleLabel.text = test
}
}
}
첫번째 화면에서 두번째 화면으로 노티로 받을경우에는 뷰디드 로드에서 진행한다.. 추후에 화면에 업데이트 된다면?? ViewWillAppear, ViewDidAppear 호출을 진행하여 사용하면 된다고 생각된다.
추가적인 노티피케이션 공부한 내용: https://hackmd.io/XLJO7Uk-S8O5Qehw9_3zew
'iOS' 카테고리의 다른 글
메모리 구조 와 ARC (0) | 2023.08.30 |
---|---|
SOLID (0) | 2023.08.22 |
싱글톤 Singleton (0) | 2023.08.22 |
MVVM 패턴에 대해서 알아보기 (0) | 2023.01.16 |
RxSwift에 대해 알아보기! (Observable) (0) | 2023.01.11 |