如何在另一个视图控制器中调用NSNotificationCenter功能?

pix*_*abs 2 iphone xcode notifications objective-c ios

可能重复:
我可以从另一个班级观看NSNotification吗?

我目前在appDelegate.m文件中使用以下代码:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(handleEnteredBackground:) 
                                             name: UIApplicationDidEnterBackgroundNotification
                                           object: nil];

}
Run Code Online (Sandbox Code Playgroud)

但是,我希望它在我的viewController.m文件中调用一个选择器.我怎样才能做到这一点?

谢谢!

Ala*_*ino 7

通常,您首先在viewController.m init方法(或其他适当的地方)注册通知:

[[NSNotificationCenter defaultCenter] addObserver: self
                                         selector: @selector(someMethod:) 
                                             name: @"NotificationNameHere"
                                           object: nil];
Run Code Online (Sandbox Code Playgroud)

在您的App Delegate中,触发通知:

- (void)applicationDidEnterBackground:(UIApplication *)application
{

    [[NSNotificationCenter defaultCenter] postNotification: @"NotificationNameHere"];

}
Run Code Online (Sandbox Code Playgroud)