How to add an Observer to your class

- by

Observers are a great way to call a method in a class when you don’t have direct access to it. If you can’t figure out what relationship this class has to the one you want to call the method from, Observers are a very easy way to send a message and trigger an action.

In the Master/Detail template for example, the Master View can update the detail view due to the View Controller relationship. But the other way round isn’t so easy – that’s where an Observer can come in handy.

First we setup the Observer in the class which contains the method we’d like to use:

// add observer
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethod) name:@"myMessage" object:nil];

The viewDidLoad method is a good place for this if it’s available. The two important parameters here are the selector which needs to be set to your existing method, and the name which is an arbitrary name that the observer listens to. You may also remove the observer when you’re done, perhaps in the viewDidUnload method (where available):

// remove observer
    [[NSNotificationCenter defaultCenter]removeObserver:self];

Next we’ll call the Observer from the other class like this:

    NSNotification *notification = [NSNotification notificationWithName:@"myMessage" object:self];
    [[NSNotificationCenter defaultCenter]postNotification:notification];

This will trigger the myMethod method in your other class.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.