0

I want to access to an IBOutlet of my first Viewcontroller by AppDelegate class. My project is based with a storyboard and there isn't the reference with the first Viewcontroller. What's the to do it? I know that I should set this IBOutlet as a property in first Viewcontroller, but in AppDelegate? How I can access to it? Thanks

2
  • 1
    Why do you need to do that? Maybe your app architecture/design is not good.
    – Larme
    Feb 26, 2014 at 14:23
  • do you set this viewController as the rootViewController of your app's window somewhere ? Feb 26, 2014 at 14:26

3 Answers 3

0

You can access your rootViewController from your app's delegate with :

self.window.rootViewController

Example :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    MyVCClass *firstVC = (MyVCClass*)self.window.rootViewController;
    [firstVC someMethod];

}

Careful, your ViewController may not have been yet loaded / initiated.

3
  • So, what's the way to call my FirstViewController? Feb 26, 2014 at 14:29
  • @nazz_areno I added an example
    – rdurand
    Feb 26, 2014 at 14:34
  • @rdurand, the rootViewCotnroller might be nil in storyboards Feb 26, 2014 at 14:37
0

Because you don't set the rootViewController for your app's UIWindow, then doing
[[UIApplication sharedApplication].keyWindow rootViewController] will give you nil.

If you use storyboards for your navigation then simply you can do this to get the rootViewController

UIViewController *vc = [self.navigationController.viewControllers objectAtIndex:0];
0

First import your ViewController in AppDelegate.m like this :

#import "YourViewController"

Then in AppDelegate.m place the below code

 @implementation AppDelegate

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:   (NSDictionary *)launchOptions
 {

   YourViewController * view = [[YourViewController alloc]init];
    self.window.rootViewController = view;
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.