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

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

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

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

在 FirstViewController.m 我有...

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

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

【问题讨论】:

    标签: iphone objective-c


    【解决方案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。很有魅力!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-11-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-20
        • 2015-10-13
        • 1970-01-01
        相关资源
        最近更新 更多