postNotificationName未调用观察者方法

10
我正在尝试使用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个回答

17

只需改变一种方式...

首先添加观察者

[[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在观察者创建之前被调用,现在问题是...考虑到我使用故事板加载视图,我该如何在发布通知之前添加addObserver,因为postNotificationName在AppDelegate的didFinishLaunchingWithOptions中被调用,而观察者是在MainView的viewDidLoad中添加的...提前致谢。 - spacebiker
我还没有实现故事板。你最好在appdidfinishlaunching方法中尝试添加观察者。 - Rams

5
你的代码看起来还好,让我想知道你在AppDelegate中何处发布通知?
如果在视图控制器中添加观察者之前发布通知,则通知将永远不会被接收。你是否可以直接将消息发送到主视图控制器,例如作为一个属性,而不是使用通知?

嗨伙计,谢谢回复。通知是在didFinishLaunchingWithOptions中发布的,观察者是在MainView的viewDidLoad中创建的,因为我正在使用故事板,所以MainView加载得太晚了。你有什么建议吗? - spacebiker

0

在这里想要注意的是,iOS通知名称是区分大小写的:

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

不会响应:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接