2012-03-13 78 views
8

我想打电话给使用NSNotificationCenter无济于事从AppDelegate中一个的UIView内的方法..postNotificationName没有要求观察者方法

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 

但它永远不会被调用。

感谢您的帮助!

+1

那么,你发布了一个通知,并_after_你注册一个观察员呢? – JiaYow 2012-03-13 10:54:07

回答

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

哇!那很快。感谢您的回复。你指出我正确的方向。 postNotificationName在观察者被创建之前被调用,所以现在的问题是......考虑到我使用storyboard加载视图,我怎么能在发布notificacion之前将它添加到addObserver中,因为postNotificationName在AppDelegate的didFinishLaunchingWithOptions和observer中被调用是从MainView的viewDidLoad中添加的。在此先感谢 – spacebiker 2012-03-13 11:02:56

+0

我还没有实现storyboard..Better你尝试adddserver在appdidfinishlaunching方法。 – Rams 2012-03-13 11:16:38

4

您的代码看起来不错,这让我想知道你的应用程序委托在哪里发布通知?

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

+0

喜队友,感谢您的答复。通知发布在didFinishLaunchingWithOptions中,观察者在MainView的viewDidLoad中创建,因为我使用的是故事板,MainView加载太迟。你有什么建议吗? – spacebiker 2012-03-13 11:07:30

0

只是想在这里指出,iOS的通知名称区分大小写

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

将不回应:

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

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