Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an NSNotification observer that may not exist

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.

like image 672
Miek Avatar asked Sep 18 '25 18:09

Miek


1 Answers

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]];

like image 159
Thompson Avatar answered Sep 21 '25 13:09

Thompson