简体   繁体   中英

How to remove noitification observer in another class?

I have created a notification in class-A like

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(methodcalled:) name:@"ViewChanged" object:nil];

I am posting this notification with name in class-B like

    [[NSNotificationCenter defaultCenter]postNotificationName:@"ViewChanged" object:nil];

Now I want to remove this notification like below in class-C. Is it possible? As I need to go to class-A from class-c.

     [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ViewChanged" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:nil name:@"ViewChanged" object:nil];
     [[NSNotificationCenter defaultCenter] removeObserver:self];

I tried but the notification is not removing and its calling two times. How to create object for NSNotificationCenter ?

[[NSNotificationCenter defaultCenter] removeObserver:nil name:@"ViewChanged" object:nil];

Your code is not working since the first parameter to removeObserver is nil, as explained in the documentation.

- (void)removeObserver:(id)notificationObserver name:(NSString *)notificationName object:(id)notificationSender

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.

A possible solution:

objectA could listen for a second notification, such as removeA . You then create a method within objectA which removes objectA as the observer for ViewChanged . removeA should trigger that method.

objectC would then only have to post the removeA notification and objectA would stop listening.

As @Wain correctly says, it's weird/wrong design. Buy if you really want to, you need to do:

[[NSNotificationCenter defaultCenter] removeObserver:objectA name:@"ViewChanged" object:nil];

So objectA is the object you passed as self when you called addObserver: . That you now need to get objectA to the instance of class C is an indication that what you're trying to do is wrong/weird.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM