Reputation: 1137
I can not seem to find a definitive answer on this topic.
Is it okay to remove an observer that may not exist?
Example Code:
-(void)commonInit{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(userDidChangePrecision:)
name:kUser_Changed_Precision
object:nil];
}
-(void)dealloc{
[[NSNotificationCenter defaultCenter]removeObserver:self];
[super dealloc];
}
This would prevent more than one observer being initialized for the object in the case where the object may be reinitialized during run time.
Upvotes: 4
Views: 1176
Reputation: 81868
I can't find definitive documentation on if it's allowed to remove non-existent observers but I think the NSNotificationCenter
documentation can be read in this way. It says that removeObserver:name:object:
removes matching observers. I'm just assuming that this includes no matching observers.
But here's another reason why your approach might be harmful: When your commonInit
method is being called other code (sub- or superclasses' init) might already have registered to notifications. When subclassing a UIViewController
that's even likely (for memory warnings).
So I'd say you should never unconditionally unregister from notification center, except in dealloc.
Upvotes: 3
Reputation: 1098
Snippet from the Apple docs:
- (void)removeObserver:(id)notificationObserver
Parameters
*notificationObserver*
The observer to remove. Must not be nil.
- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender
Parameters
*notificationObserver*
Observer to remove from the dispatch table. Specify an observer to remove only entries for this observer. Must not be nil, or message will have no effect.
In both cases, the warning that observer not be nil is overstated; the effect, in both cases, is that this message has no effect. Neither compiler nor runtime errors, no zombies, &c.
Likewise, specifying an observer that is not observing also has no effect.
Not a definitive answer, but based on observations and investigations of playing with trial-and-error code such as:
[[NSNotificationCenter defaultCenter] removeObserver:nil];
[[NSNotificationCenter defaultCenter] removeObserver:[UIView new]];
Upvotes: 3