简体   繁体   English

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

[英]How to call function in ViewController.m from AppDelegate?

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


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

I use this code, but get error: 我使用此代码,但出现错误:

ld: 110 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) ld:架构x86_64 clang的110个重复符号:错误:链接器命令失败,退出代码为1(使用-v查看调用)

How to fix? 怎么修?

110 duplicate symbols means you have a lot more problems than trying to call your view controller's serverSync function from your app delegate. 110 duplicate symbols表示,与尝试从应用程序委托中调用视图控制器的serverSync函数相比,您遇到的问题要serverSync

Instead of doing serverSync within your app delegate, put it in your view controller's viewDidLoad method. 与其在您的应用程序委托中进行serverSync将其放入视图控制器的viewDidLoad方法中。

Even better, create a singleton object that does the serverSync and your view controller can access and use your server data from there. 更好的是,创建一个执行serverSync的单例对象,并且视图控制器可以从那里访问和使用服务器数据。

You can use NSNotificationCenter for this. 您可以为此使用NSNotificationCenter。 Here is the example. 这是例子。

In your AppDelgate.m 在您的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.
}

In your ViewController.m 在您的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!");
}

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

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