How to pass data from the App Delegate to your Top View Controller

If the App Delegate has something that your top view controller needs then you simply pass it the required object via a property set on the top view controller. This is easy when your top view controller is also the root view controller.

However, when you embed your top view controller in a Navigation Controller, and perhaps that one is also embedded in a Tab Bar Controller, then this array isn’t quite so easy to figure out (and I must admit that I always forget how to do this when a new challenge arises).

So here’s how this works. In this example, the thing that’s displayed is called MyViewController, which is embedded in a Navigation Controller. I’m passing it the App Delegate’s self.managedObjectContext which is defined as a property on MyViewController.

We call this in the applicationDidFinishLaunching method, just before the return statement.

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.

4 thoughts on “How to pass data from the App Delegate to your Top View Controller

  1. If you embed your Navigation Controllers into a Tab Bar Controller you’ll have to go one step further up the food chain. To stay with the above example, you’d first grab a reference to your Tab Bar Controller, then grab the viewControllers array and pass each Navigation Controller an instance separately:

      1. Hi April,

        sure thing – it’s all based on the code you get when you open a new Master/Detail protect with Core Data. Xcode provides this stub under applicationDidFinishLaunching, extracting the view controller from a split view by default. Choose Swift and you’ll see how it’s done in Swift, then tweak it to your own needs.

  2. Alternatively you can import AppDelegate.h into the class you’d like to use Core Data in, and grab the managedObjectContext from there.

    Here’s a custom initialiser that does this:

Leave a Reply

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