Netnyke
Netnyke

Reputation: 151

Calling view controller method from app delegate

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 {
     [..]
}

Upvotes: 10

Views: 30618

Answers (5)

Sruit A.Suk
Sruit A.Suk

Reputation: 7273

In Swift, you can write it like this

    UIApplication.sharedApplication().keyWindow?.rootViewController?.yourMethodName()

Upvotes: 2

luismesas
luismesas

Reputation: 352

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.

Upvotes: 7

trojanfoe
trojanfoe

Reputation: 122458

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.

Upvotes: 11

Louie
Louie

Reputation: 5940

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

Upvotes: 13

Manlio
Manlio

Reputation: 10864

Try to write

 -(void) myMethodHere;

in MainViewController.h

Upvotes: 0

Related Questions