[swift] NotificationCenter 사용하기
* NotificationCenter 사용하기
IOS 에서 Background로 받은 데이터를 처리할 때 주로 NotificationCenter를 사용한다
등록 할 때는
NotificationCenter.default.addObserver(self, selector: #selector(self.AAA()), name: NSNotification.Name(rawValue: "BBB"), object: nil) |
위에서 AAA()는 다른 곳에서 post했을 시 해당 함수로 이동할 수 있도록 등록하는것이고 , BBB는 다른 곳에서 post 할 때 값으로 이름을 서로 정해논 것이다.
한마디로 정리하면 다른곳에서 이 AAA() 함수를 실행 시키기 위해서 "BBB"를 value로 설정하여 알림을 보내주면 등록되어 있는 Notification중에 "BBB"를 찾아 AAA() 함수를 실행 시켜줄 수 있는것이다.
다른 곳에서 이 것을 호출 할 시에는
NotificationCenter.default.post(name: Notification.Name(rawValue: "BBB"), object: self) |
이런 식으로 사용한다.
또한 해제 할 시에는
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "BBB"), object: nil) |
이런 식으로 사용한다.
보통 페이지를 시작할 때 등록해주고 페이지를 닫아 줄 때는 해지 시켜 주면서 사용한다.