Tag Archives: NSNotification

How to check if your iOS App comes into the foreground or background

I’ve been battling with those AppDelegate methods for a while, thinking “I wish there was a way that I don’t have to use those methods”. And guess what: there is!

Instead of adding code where it doesn’t make sense, we can listen to a system wide notification that tells us our app has come into the foreground, like so:

Here the selector “myMethod” is called when our app is about to enter the foreground. Some of the interesting notifications are

  • UIApplicationDidEnterBackground
  • UIApplicationDidEnterForeground
  • UIApplicationWillTerminate

Find many more in Apple’s UIApplication Class Reference:

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.