Swiftlint: Rule request: Discarded opaque NSNotificationCenter observer

Created on 25 Dec 2016  路  5Comments  路  Source: realm/SwiftLint

From http://fauxpasapp.com/rules/#rule-DiscardedOpaqueNotificationObserver:


Warns if the return value of -[NSNotificationCenter addObserverForName:object:queue:usingBlock:] is not stored anywhere. This method returns an opaque observer object that is needed in order to stop observing.

rule-request

Most helpful comment

Yes, because that only works when using the selector-based methods.

All 5 comments

Is this still necessary with the automatic unobserving in iOS 9 and later?

Yes, because that only works when using the selector-based methods.

Guys, what do you think about this research https://oleb.net/blog/2018/01/notificationcenter-removeobserver/ ?

@marcelofabri That's not how I interpret the documentation

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method. Otherwise, you should call this method or removeObserver:name:object: before observer or any object specified in addObserverForName:object:queue:usingBlock: or addObserver:selector:name:object: is deallocated.

The first sentence implies after iOS 9.0 you don't need to explicitly unregister the observer no matter the method used. Where did you learn that automatic unregister only works for selector-based methods?

@daltyboy11 It's trivially confirmable experimentally, as done in the blog post linked just above you by @bimawa. The documentation for addObserver(forName:object:queue:using:) is also pretty clear:

You must invoke removeObserver(_:) or removeObserver(_:name:object:) before any object specified by addObserver(forName:object:queue:using:) is deallocated.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

BalestraPatrick picture BalestraPatrick  路  3Comments

Tableau-David-Potter picture Tableau-David-Potter  路  3Comments

mildm8nnered picture mildm8nnered  路  3Comments

rajohns08 picture rajohns08  路  3Comments

ziryanov picture ziryanov  路  3Comments