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)
}
Related videos on Youtube
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, 2022Comments
-
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 about 11 yearsSee this question.
-
Anoop Vaidya about 11 yearsThis is same as I asked few months back :)
-
amergin over 10 yearsI 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 over 9 yearsI 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 almost 10 yearsOne question: When you call addObserver, is NSNotificationCenter retaining the observer or not? Thanks.
-
holex over 9 yearsthe notification center won't hold strong references of the observers, so there is not necessary to remove them explicitly in
ARC
. -
Honghao Zhang over 9 yearsIt'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 almost 8 yearsThis answer is outdated since iOS9, unregistering in dealloc is no longer needed, ref: useyourloaf.com/blog/…