10

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 {
     [..]
}
Netnyke
  • 151
  • 1
  • 1
  • 8

5 Answers5

13

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
Louie
  • 5,920
  • 5
  • 31
  • 45
  • 4
    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?? – Supertecnoboff Mar 26 '16 at 16:35
11

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.

trojanfoe
  • 120,358
  • 21
  • 212
  • 242
7

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.

luismesas
  • 342
  • 5
  • 5
2

In Swift, you can write it like this

    UIApplication.sharedApplication().keyWindow?.rootViewController?.yourMethodName()
Sruit A.Suk
  • 7,073
  • 7
  • 61
  • 71
0

Try to write

 -(void) myMethodHere;

in MainViewController.h

Manlio
  • 10,768
  • 9
  • 50
  • 79