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:

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):

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

This will trigger the myMethod method in your other class.

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Leave a Reply

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