如何从 AppDelegate 调用在 ViewController 中声明的方法

Posted

技术标签:

【中文标题】如何从 AppDelegate 调用在 ViewController 中声明的方法【英文标题】:How to call a method that's declared in a ViewController from the AppDelegate 【发布时间】:2010-07-21 16:00:21 【问题描述】:

新手问题。我正在构建一个应用程序,我想从 AppDelegate(在 applicationDidBecomeActive 上)调用我在 ViewController 中声明的方法。

所以基本上,在 TestAppDelegate.m 我有...

- (void)applicationDidBecomeActive:(UIApplication *)应用 // 我想调用我定义的名为“dothisthing”的方法 第一视图控制器.m // 这不起作用:[FirstViewController dothisthing]

在 FirstViewController.m 我有...

-(无效)做这件事 NSLog(@"dothisthing");

这是我的第一个 iPhone 应用程序,如有任何帮助,我们将不胜感激。

【问题讨论】:

【参考方案1】:

该方法是一个实例方法,所以你需要先创建实例,然后在实例上调用该方法......或者在void之前将方法声明为静态(+)而不是(-)

FirstViewController* controller = [FirstViewController alloc];

[controller dothisthing]; 

[controller release];

【讨论】:

感谢您的澄清。我不确定我应该首先在哪里创建实例。在 AppDelegate.m 中?完整的 Obj-C 新手在这里。 嗯,这取决于你的控制器的生命周期......如果这是你的应用程序中的主/唯一控制器,那么 appDelegate 应该“拥有”控制器(在@interface中声明它) ,在applicationDidFinishLoading中实例化,在dealloc中释放) 谢谢!我的工作正常,但还有一个问题……我收到警告:FirstViewController 可能无法响应“-dothisthing”代码如下: FirstViewController *controller = [FirstViewController alloc]; [控制器做这件事]; // 这会引发警告 不看代码可能很难说,但您可能在接口 (.h) 文件中缺少 dothisthing 方法的声明,或者签名可能与您的方式不匹配'正在调用它(即声明中的参数而不是使用参数调用它)【参考方案2】:

您还可以在 FirstViewController 中创建一个通知,以便在您的应用程序变为活动状态时调用该方法。

有一个类似的问题,我在其中发布了该选项的代码 sn-ps

How to refresh UITableView after app comes becomes active again?

【讨论】:

【参考方案3】:

使用这个简单的NSNotificationCenterexample。很有魅力!

【讨论】:

以上是关于如何从 AppDelegate 调用在 ViewController 中声明的方法的主要内容,如果未能解决你的问题,请参考以下文章

如何从 UI Xctest 调用 Appdelegate 的“OpenURL”功能

如果我使用 TabBar Navigation,如何从 AppDelegate 调用 viewcontroller 方法

如何从 ViewController 或其他地方调用或触发 AppDelegate 中的通知功能?

如何从 AppDelegate.m 调用 ViewController.m 方法

如何快速添加从我的 appdelegate 类调用的弹出窗口?

在 appDelegate 中的 didReceiveRemoteNotification 方法的 Present 模式后推送控制器