ios - 从 AppDelegate 发送 NSNotification

标签 ios objective-c nsnotification

我想发送 NSNotification在我的 AppDelegate.m 中使用此方法(单击 UIButton 时):

- (void)alertView:(UIAlertView *)alertView 
        clickedButtonAtIndex:(NSInteger)buttonIndex{

if (buttonIndex == 0){
    //cancel clicked ...do your action
    // HERE
}
}

..并通过我的 UIViewControllers 之一接收它.我怎样才能做到这一点?

编辑更多信息:我正在制作一个闹钟应用程序,当用户按下 UIButton , 我想停止闹钟。我认为 NSNotifications是从我的 AppDelegate.m 文件获取信息到 ViewController.m 文件的唯一方法吗?

最佳答案

您应该注册您的接收器对象以接受从通知中心发送的一些消息。

假设你有 Obj A 来控制你的闹钟,并且值“stopAlarm”是可以停止闹钟的消息。您应该为“stopAlarm”消息创建一个观察者。

你可以这样做:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(controller:)
                                             name:@"stopAlarm"
                                           object:nil];

现在,您应该创建一个管理这些消息的方法 Controller :
 - (void)controller:(NSNotification *) notification {

     if ([[notification name] isEqualToString:@"stopAlarm"]){

         //Perform stop alarm with A object
     }
  }

最后,您可以根据需要在代码中发送消息“stopAlarm”:
[[NSNotificationCenter defaultCenter]
     postNotificationName:@"stopAlarm"
     object:nil];

我希望这可能会有所帮助。

编辑:

当您的 UIViewController 被卸载或应用程序终止时,您应该调用:
    [[NSNotificationCenter defaultCenter] removeObserver:self];

停止观察。
就这样。

感谢 Hot licks 的纠正。

关于ios - 从 AppDelegate 发送 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20454973/

相关文章:

objective-c - 可以在 Interface Builder/Cocoa 中改变颜色的简单方 block

ios - 无法找到 NSNotification 的发件人

iphone - 什么是 NSNotification?

ios - 如何在 swift 3 中访问使用语音备忘录或其他录音机应用程序录制的录音

ios - Google Maps iOS SDK 链接错误 "Undefined symbols for architecture arm64"

iphone - 在 UIImage 上绘制另一个图像

objective-c - 有没有办法识别 NSNotification/NSEvent 来自哪个应用程序?

ios - 放大屏幕中央 - Google Maps iOS SDK Swift

ios - AWS Mobile hub with Cocoa pods Apple Mach-O 链接器错误

ios - 添加一个事件指示器以显示应用程序何时在 jquery mobile、phonegap/cordova 中忙碌