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

5 Answers 5

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
Sign up to request clarification or add additional context in comments.

1 Comment

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??
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.

Comments

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.

Comments

2

In Swift, you can write it like this

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

Comments

0

Try to write

 -(void) myMethodHere;

in MainViewController.h

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.