Reputation: 151
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
Reputation: 7273
In Swift, you can write it like this
UIApplication.sharedApplication().keyWindow?.rootViewController?.yourMethodName()
Upvotes: 2
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
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
Reputation: 5940
I would try
MainViewController * vc = [[MainViewController alloc]init];
[vc myMethodHere];
[vc release];
.m
file.h
fileUpvotes: 13