postNotificationName不调用observer方法

时间:2012-03-13 10:45:06

标签: iphone xcode nsnotificationcenter

我试图使用NSNotificationCenter从AppDelegate调用uiview中的方法无济于事。

AppDelegate.m

    [[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];

然后通过MainStoryboard,加载主视图,哪个控制器类是MainViewController

在MainViewController.h中viewDidLoad我有

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

然后是方法

- (void) ProcessDidComplete:(NSNotification *)pNotification

但永远不会被召唤。

感谢您的帮助!

3 个答案:

答案 0 :(得分:15)

只是改变一种方式..

首先添加观察者

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

然后发布通知

 [[NSNotificationCenter defaultCenter] postNotificationName:@"ProcessDidComplete" object:items];

最后在viewWillDisappear中删除

 [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ProcessDidComplete" object:nil];

答案 1 :(得分:5)

您的代码看起来没问题,这让我想知道您的应用委托发布通知的位置在哪里?

如果在视图控制器中添加观察者之前发布通知,则永远不会收到通知。您是否可以直接将消息发送到主视图控制器,即作为属性,而不是使用通知?

答案 2 :(得分:0)

只是想在此注意iOS通知名称​​区分大小写

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

不会回复:

[[NSNotificationCenter defaultCenter] postNotificationName:@"ScheduleUpdated" object:items];

(因为我花了最后20分钟搞清楚......)