Calling view controller method from app delegate

30,319

Solution 1

I would try

MainViewController * vc = [[MainViewController alloc]init];
[vc myMethodHere];
[vc release];
  1. Make sure to import your MainViewController in your app delegate .m file
  2. make sure you add "myMethodHere" to your MainViewController .h file

Solution 2

You are trying to call a class method when you want to call an instance method. If the view controller is the root view controller, then you should be able to call it thus:

UIWindow *window = [UIApplication sharedApplication].keyWindow;
MainViewController *rootViewController = window.rootViewController;
[rootViewController myMethodHere];

If it's not the root view controller then you'll have to find some other way of getting hold of the instance and then calling the method as in the last line above.

Solution 3

If you want to access to a view controller on a story board, you may use this block of code from the AppDelegate:

MainViewController *rootViewController = (MainViewController*)self.window.rootViewController;
[rootViewController aMethod];

Remember to add the import.

Solution 4

In Swift, you can write it like this

    UIApplication.sharedApplication().keyWindow?.rootViewController?.yourMethodName()
Share:
30,319
Netnyke
Author by

Netnyke

Updated on July 05, 2022

Comments

  • Netnyke
    Netnyke almost 2 years

    I'm trying to call a method in the view controller from the app delegate, but Xcode says No known class method for selector 'myMethodHere'. Here's my code:

    AppDelegate.m:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [..]
                [MainViewController myMethodHere];
        [..]
        return YES;
    }
    

    MainViewController.m:

    -(void) myMethodHere {
         [..]
    }
    
  • Supertecnoboff
    Supertecnoboff over 8 years
    Im not too sure if this works though. Doesn't this create another instance of the view you are trying to access? Lets say you are trying to run a method in that view controller, but the method is dependant on a certain bit of UI/data in that view, then doing this won't work, as the instance you have created does not contain that data right??