일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
- noncopyable
- 알고리즘
- 구조체
- 자바
- 프래그먼트
- 백준
- 리스트뷰
- observable
- 프로그래머스
- ios
- 안드로이드
- 클로저
- 스위프트
- 차이
- 이스케이핑
- rx
- 해시
- 프로퍼티
- 생명주기
- RxSwift
- 풀이
- weak
- Swift
- Subject
- 옵셔널
- View
- async
- 연산자
- concurrency
- Self
- Today
- Total
study record
[iOS] NotificationCenter 본문
NotificationCenter
NotificationCenter에 등록된 이벤트가 발생하면 해당 이벤트에 대한 행동을 취한다.
앱 내에서 메세지를 던지면 어디에서나 이 메세지를 받을 수 있게 한다.
보통 백그라운드 작업의 결과, 비동기 작업의 결과 등 현재 작업의 흐름과 다른 흐름의 작업으로부터 이벤트를 받을 때 사용한다.
싱글턴 객체 중 하나로, 이벤트들의 발생 여부를 옵저버를 등록한 객체들에게 Notification을 post하는 방식으로 사용한다.
Notification Name이라는 Key 값을 통해 보내고 받을 수 있다.
NotificationCenter는 notifiaction을 발송하면 NotificationCenter에서 메세지를 전달한 observer의 처리가 완료될 때까지 대기한다(동기). 비동기적으로 사용하려면 NotificationQueue를 사용해야 한다.
- 언제 사용?
하나의 VC가 아닌 여러 개의 VC를 통제하고 싶을 때. 1:N 상황에 더 유용.
상호작용이 반복적으로, 지속적으로 이루어져야 할 때.
// 노티피케이션 발송
NotificationCenter.default.post(name: NSNotification.Name("TestNotification"), object: nil, userInfo: nil)
// 옵저버 등록
NotificationCenter.default.addObserver(self, selector: #selector(didRecieveTestNotification(_:)), name: NSNotification.Name("TestNotification"), object: nil)
@objc func didRecieveTestNotification(_ notification: Notification) {
print("Test Notification")
}
Notification의 종류
- Notification: 일반적으로 사용하는데 사용하는 Notification
- Local Notification : 특정 시간에 알림이 날라오게 하는데 활용하는 Notification
- Remote Notification : 앱에서 알림이 날라오게 할 때 사용하는 Notification
Notification 실행 로직
- sender 객체에서 Notification 생성 후 NotificationCenter에 보낸다.
- 특정 Notification이 들어오면 실행하고 싶은 로직은 addObserver 메서드를 이용해 NotificationCenter 객체에 등록한다.
- sender 객체에서 보낸 Notification이 NotificationCenter 객체의 Dispatch Table에 저장된다.
- 저장된 Notification을 활용하는 Observer들에게 Notification이 들어왔음을 알려준다.
- OBserver 실행
참고:
https://silver-g-0114.tistory.com/106
https://leeari95.tistory.com/49
https://velog.io/@cooo002/ios-Notification%EC%9D%98-%ED%99%9C%EC%9A%A9
'iOS > iOS 정리' 카테고리의 다른 글
[iOS] View의 생명주기 (0) | 2022.03.23 |
---|---|
dequeueReusableCell(withIdentifier:for:) 의미와 장점 (0) | 2022.03.17 |
[iOS] AppDelegate, SceneDelegate (0) | 2022.03.10 |
[iOS] 왜 GCD(Grand Central DispatchQueue)를 사용하는가? (0) | 2022.03.07 |
[iOS] iOS TextView 행간, 자간 조절하기 (0) | 2022.03.02 |