How to add an Observer to your class

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.





Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.