我想发送 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/