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

- by

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.

// grab our own navigation controller
UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
    
// grab our table view controller
MyViewController *myViewController = (MyViewController *)navigationController.topViewController;
    
// pass in whatever data you need (such as this):
myViewController.managedObjectContext = self.managedObjectContext;

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



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

Add your voice!

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