Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Observer when using addObserverForName:usingBlock

I have the following code that adds an observer in the loading of the view.

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserverForName:@"com.app.livedata.jsonupdated"
                                                      object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
                                                          NSLog(@"JSONUPDATED");
                                                      }];
}

And this fires fine. However when the view is unloaded and I confirm the dealloc is called the Notification is still firing.

There doesn't seem to be a method for deactivating this observer?

like image 630
Lee Armstrong Avatar asked Jan 17 '12 07:01

Lee Armstrong


People also ask

How do I delete an observer in Objective C?

When removing an observer, remove it with the most specific detail possible. For example, if you used a name and object to register the observer, use removeObserver:name:object: with the name and object.

Do I need to removeObserver?

specifies. If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:) , you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it.

How do you delete observers in Swift?

Removing registered observer For Selector approach, use NotificationCenter. default. removeObserver(self, name: notificationName , object: nil) , to remove the observer. For Block based approach, save the token you obtained by registering for notification in a property.

What is NotificationCenter default addObserver?

default — This is the notification variable you can create it globally inside your class if you having more notifications. addObserver(self, — This is for the class where we are going to observer notification.


1 Answers

Seems the solution is to track the object in the View and then you can reference it in the dealloc methods.

 id observer = [[NSNotificationCenter defaultCenter] addObserverForName: /* ... */ ];

And then remove as following:

[[NSNotificationCenter defaultCenter] removeObserver:observer];
observer = nil;
like image 136
Lee Armstrong Avatar answered Nov 15 '22 17:11

Lee Armstrong