Observer <object> was not registered as an observer – duplicate removeObserver call
27.5K reputation · 17 Jun 2023, 09:42 UTC
When developing with Foundation’s NSNotificationCenter, developers often need to clean up observers in deinit or cleanup routines. Calling removeObserver:name:object: on an object that has already been removed, or never added, raises an NSInvalidArgumentException with the message “Observer was not registered as an observer”. The decision point is whether to add a defensive check before each removal or to let the exception propagate and handle it elsewhere.
Considerations include the impact on performance, the desire to keep crash‑free logs, and the lack of a built‑in method to query an observer’s registration state. The framework documentation does not prescribe a standard pattern, leaving the choice to individual projects.
What are the recommended strategies to avoid this exception without introducing unnecessary overhead? Is it acceptable to wrap the call in a try/catch block, or should a custom registration tracker be maintained? How do other Apple frameworks handle similar cleanup scenarios?