我想在我的AppDelegate.m中通过此方法(单击NSNotification时)发送一个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];

现在,您应该创建一个管理以下消息的方法控制器:
 - (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];

停止观察。
就这样。

感谢热舔的纠正。

10-07 19:37
查看更多