# 노티피케이션
- 방송을 한다 95.8fm 채널 count -> 1로 변경하겠습니다 하면 95.8fm 채널 이용자들의 count 가 변경되는? 방송실에서 알렸으니 이걸 변경을 진행한다~ 이런 느낌적인 느낌
- Notification(채널?)을 발송하면 NotificationCenter(방송국!)에서 메세지를 전달한 observer를 처리할 때까지 대기한다.
- 즉, 흐름이 동기적으로 흘러간다.
- NotificationCenter(방송국!)를 통해서 어떠한 화면에서 다른 화면으로 데이터를 전달 할 수 있다.
- NotificationCenter은 언제 사용할까?
- 앱 내에서 공식적인 연결이 없는 두개 이상의 컴포넌트들의 상호작용이 필요할때 사용한다.
- 상호작용이 반복적으로 그리고 지속적으로 이루어져야 할때
- 하나의 변경을 사항을 여러곳에 보내야할때
### 처음 화면(보내는 화면)
```swift
func firstPost() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "1"), object: self.nameLabel.text)
}
```
```swift
func secondPost() {
NotificationCenter.default.post(name: Notification.Name(rawValue: "2"), object: self.phoneNumberLabel.text)
}
```
- Post
- Post는 객체가 NotificationCenter로 이벤트를 보내는 행위를 의미합니다.
```swift
@IBAction func pushView(_ sender: UIButton) {
let secondView = SecondViewController()
self.navigationController?.present(secondView, animated: true)
firstPost()
secondPost()
}
```
- 노티를 던진다? 버튼을 누르면서 화면 이동을 진행할때에 노티를 던져 줘야지만 넘어가게 된다.
### 두번째 화면(받는 화면)
```swift
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
addObserverFirst()
addObserverSecond()
}
Observer 등록 진행
func addObserverFirst() {
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 addObserverSecond() {
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
}
}
}
```
### 노티피케이션 제거하기
- Observer 제거하기
노티를 제거하지않으면 메모리에 계속 올라가 있게 되므로 변경이 되었다면 후에 해제를 해줘야한다.
```swift
deinit {
NotificationCenter.default.removeObserver(self)
}
```
- 저의 경우에는 다이어리프로젝트때 사용을 해봤습니다.
```swift
private func setUpNotification()
deinit {
NotificationCenter.default.removeObserver(self)
}
```
- 리뷰어의 피드백!

#### 전체적인 주의 사항
- 노티피케이션 사용 시 강한 참조 주의: 노티피케이션을 사용할 때, Observer의 클로저가 실행될 때 강한 참조가 발생할 수 있습니다. 그렇기에 [weak self] 사용하여 강한 참조 순환을 피하는 것이 중요합니다.
- 노티피케이션의 전역 사용에 주의: 노티피케이션은 전역 이벤트를 처리하는 데 사용되므로 다중으로 사용하면 코드의 가독성이 감소하고 디버깅이 어려워집니다. 필요한 경우에만 사용하고, 사용시에 다른 방법이 더 적절한지 고려하는 것이 좋습니다.
- ViewController에서의 Observer 제거: 노티피케이션 Observer를 등록한 ViewController가 화면에서 제거될 때, 해당 Observer를 제거하지 않으면 메모리 누수가 발생할 수 있습니다. viewWillDisappear에서도 해당 Observer를 제거하여 안전성을 높이는 것이 좋습니다.