Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {
     [..]
}
like image 814
Netnyke Avatar asked Nov 15 '11 18:11

Netnyke


People also ask

Is AppDelegate a controller?

The application delegate is a controller object. By default, it is the owner and controller of the main window -- which is a view -- in an iOS app. The app delegate receives messages from an object representing -- or modeling -- the application itself (an instance of UIApplication ).

How do I present a view controller in Objective C?

Set the modalPresentationStyle property of the new view controller to the desired presentation style. Set the modalTransitionStyle property of the view controller to the desired animation style. Call the presentViewController:animated:completion: method of the current view controller.

What is the difference between a view and a view controller?

The view renders presentation of the model in a particular format. The controller responds to the user input and performs interactions on the data model objects. The controller receives the input, optionally validates it and then passes the input to the model.


3 Answers

In Swift, you can write it like this

    UIApplication.sharedApplication().keyWindow?.rootViewController?.yourMethodName()
like image 100
Sruit A.Suk Avatar answered Nov 05 '22 10:11

Sruit A.Suk


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.

like image 38
luismesas Avatar answered Nov 05 '22 10:11

luismesas


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
like image 37
Louie Avatar answered Nov 05 '22 08:11

Louie