[iOS] Notification 중복 문제

승아·2021년 5월 1일
0

iOS Notification 노티 사용시 주의할 점

특정 이벤트를 발생 시키면 같은 Notification이 여러번 호출되는 버그 발견. NotificationCenter에 같은 Notification을 가지고 있는 옵저버를 계속 추가해줘서 발생하는 문제. 옵저버 중복 방지를 위해 옵저버를 제거하여 해결하자.

✅⠀옵저버 추가는 viewWillAppear에서

  • func addObserver(_ observer: Any, selector aSelector: Selector, name aName: NSNotification.Name?, object anObject: Any?)
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    // 옵저버 추가
    NotificationCenter.default.addObserver(self, selector: #selector(self.clickNumberNotification(_:)), name: ClickNumberNotification , object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(self.optionNotification(_:)), name: OptionNotification, object: nil)
}

✅⠀옵저버 제거는 viewWillDisappear에서

  • func removeObserver(_ observer: Any, name aName: NSNotification.Name?, object anObject: Any?) // 해당 ViewController에 특정 옵저버 제거
  • func removeObserver(_ observer: Any) // 해당 ViewController에 모든 옵저버 제거
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)
    // 모든 옵저버 제거
    NotificationCenter.default.removeObserver(self)
    // 특정 옵저버 제거
    /*NotificationCenter.default.removeObserver(self, name: ClickNumberNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: OptionNotification, object: nil)/*
}

0개의 댓글