简体   繁体   English

从app delegate调用视图控制器方法

[英]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'. 我试图从app委托调用视图控制器中的方法,但是Xcode说选择器'myMethodHere'没有已知的类方法。 Here's my code: 这是我的代码:

AppDelegate.m: AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [..]
            [MainViewController myMethodHere];
    [..]
    return YES;
}

MainViewController.m: MainViewController.m:

-(void) myMethodHere {
     [..]
}

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 确保在app delegate .m文件中导入MainViewController
  2. make sure you add "myMethodHere" to your MainViewController .h file 确保将“myMethodHere”添加到MainViewController .h文件中

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. 如果它不是根视图控制器,那么你将不得不找到一些其他方法来获取实例,然后调用上面最后一行中的方法。

If you want to access to a view controller on a story board, you may use this block of code from the AppDelegate: 如果要访问故事板上的视图控制器,可以使用AppDelegate中的以下代码块:

MainViewController *rootViewController = (MainViewController*)self.window.rootViewController;
[rootViewController aMethod];

Remember to add the import. 请记住添加导入。

在Swift中,你可以这样写

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

Try to write 试着写

 -(void) myMethodHere;

in MainViewController.h MainViewController.h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM