xcode postNotificationName 不调用观察者方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9682518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
postNotificationName not calling observer method
提问by spacebiker
I am trying to call a method within an uiview from AppDelegate using the NSNotificationCenter to no avail..
我正在尝试使用 NSNotificationCenter 从 AppDelegate 调用 uiview 中的方法无济于事..
AppDelegate.m
AppDelegate.m
[[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];
Then via MainStoryboard, the main view is loaded which controller class is MainViewController
然后通过MainStoryboard,加载主视图,哪个控制器类是MainViewController
in MainViewController.h viewDidLoad i have
在 MainViewController.h viewDidLoad 我有
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ProcessDidComplete:) name:@"ProcessDidComplete" object:nil];
and then the method
然后方法
- (void) ProcessDidComplete:(NSNotification *)pNotification
but it never gets called.
但它永远不会被调用。
Thanks for any help!
谢谢你的帮助!
回答by Rams
just change a way..
换一种方式吧。。
First add observer
首先添加观察者
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ProcessDidComplete:) name:@"ProcessDidComplete" object:nil];
Then Post Notification
然后发布通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];
Finally remove in viewWillDisappear
最后在 viewWillDisappear 中删除
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"ProcessDidComplete" object:nil];
回答by Stephen Darlington
Your code looks okay, which makes me wonder where in your app delegate you post the notification?
您的代码看起来不错,这让我想知道您在应用委托中发布通知的位置?
If you post the notification before you add the observer in the view controlller, then the notification will never be received. Can you not send the message to the main view controller directly, i.e., as a property, rather than using notifications?
如果在视图控制器中添加观察者之前发布通知,则永远不会收到通知。你能不能不直接将消息发送到主视图控制器,即作为一个属性,而不是使用通知?
回答by adamup
Just wanted to note here that iOS notification names are case-sensitive:
只是想在这里注意,iOS 通知名称区分大小写:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handUpdate:) name:@"scheduleUpdated" object:nil];
will not respond to:
不会回应:
[[NSNotificationCenter defaultCenter] postNotificationName:@"ScheduleUpdated" object:items];
(as I spent the last 20 minutes figuring out...)
(因为我花了最后 20 分钟弄清楚......)