43

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?

bneely
  • 9,083
  • 4
  • 38
  • 46
Tudor
  • 4,137
  • 5
  • 38
  • 54
  • See [this question](http://stackoverflow.com/q/13911651/730701). – Adam Mar 27 '13 at 10:17
  • This is same as I asked few months back :) – Anoop Vaidya Apr 03 '13 at 06:01
  • 2
    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. – amergin Nov 27 '13 at 12:03
  • 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? – Jing Feb 02 '15 at 03:22

1 Answers1

80

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)
       }
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
  • One question: When you call addObserver, is NSNotificationCenter retaining the observer or not? Thanks. – Ricardo May 14 '14 at 14:53
  • 3
    the notification center won't hold strong references of the observers, so there is not necessary to remove them explicitly in `ARC`. – holex Oct 29 '14 at 16:51
  • It's do need to remove observer in `deinit` method. I've seen crashes related to NSNotificationCenter and it's resolved by removing observer – Honghao Z Feb 07 '15 at 06:28
  • 20
    This answer is outdated since iOS9, unregistering in dealloc is no longer needed, ref: http://useyourloaf.com/blog/unregistering-nsnotificationcenter-observers-in-ios-9/ – Bradley Thomas Jun 15 '16 at 14:02