如何从AppDelegate调用ViewController.m中的函数?

时间:2017-01-27 13:09:18

标签: ios objective-c iphone

- (void)applicationDidBecomeActive:(UIApplication *)application {
    UIViewController* root = _window.rootViewController;
    UINavigationController* navController = (UINavigationController*)root;


    UIViewController  mycontroller = (UIViewController )[[navController viewControllers] objectAtIndex:0];
    [mycontroller serverSync];
}

我使用此代码,但收到错误:

ld:110个用于体系结构x86_64的重复符号 clang:错误:链接器命令失败,退出代码为1(使用-v查看调用)

如何解决?

2 个答案:

答案 0 :(得分:2)

110 duplicate symbols表示您遇到的问题比尝试从您的应用代表调用视图控制器的serverSync功能要多得多。

不要在您的应用委托中执行serverSync,而是将其放在视图控制器的viewDidLoad方法中。

更好的是,创建一个执行serverSync的单例对象,您的视图控制器可以从那里访问和使用您的服务器数据。

答案 1 :(得分:0)

您可以使用NSNotificationCenter。这是一个例子。

在你的AppDelgate.m

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"iOStpoint.wordpress.com"
     object:self];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

在ViewController.m中

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"iOStpoint.wordpress.com"
                                               object:nil];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void) receiveTestNotification:(NSNotification *) notification
{

    if ([[notification name] isEqualToString:@"iOStpoint.wordpress.com"])
        NSLog (@"Successfully received the test notification!");
}