Is NSNotificationCenter removeObserver in ARC needed?

15,082

You should explicitly remove the observer even you use ARC. Create a dealloc method and remove there..

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

If you see the method you don't need to call [super dealloc]; here, only the method without super dealloc needed.

UPDATE for Swift

You can remove observer in deinit method if you are writing code in swift.

deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
       }
Share:
15,082

Related videos on Youtube

Tudor
Author by

Tudor

Obj-C developer, Pythonista TDD-ing. Having a good sense for UI and UX, improving the world in my spare time. http://www.tudormunteanu.com

Updated on June 07, 2022

Comments

  • Tudor
    Tudor almost 2 years

    Does adding an observer increase the retain count of an object? If yes, does ARC handle the removing of this observer too? If not, where should I remove the observer?

    • Adam
      Adam about 11 years
    • Anoop Vaidya
      Anoop Vaidya about 11 years
      This is same as I asked few months back :)
    • amergin
      amergin over 10 years
      I think it's valid re-asking these questions as I prefer to look for the newest answers to questions in case the perceived wisdom has changed.
    • Jing
      Jing over 9 years
      I tested and found that not calling removeObserver in dealloc won't lead to crash when observed object post notifications. Since addObserver not retain observer, is it still need to removeObserver?
  • Ricardo
    Ricardo almost 10 years
    One question: When you call addObserver, is NSNotificationCenter retaining the observer or not? Thanks.
  • holex
    holex over 9 years
    the notification center won't hold strong references of the observers, so there is not necessary to remove them explicitly in ARC.
  • Honghao Zhang
    Honghao Zhang over 9 years
    It's do need to remove observer in deinit method. I've seen crashes related to NSNotificationCenter and it's resolved by removing observer
  • Bradley Thomas
    Bradley Thomas almost 8 years
    This answer is outdated since iOS9, unregistering in dealloc is no longer needed, ref: useyourloaf.com/blog/…