2

我正在使用 xcode 和 Objective c 开发 ios 应用程序 ios 5+。好的,目前正在搞乱 nsnotifications,我只需要一些澄清,因为我有点困惑。假设我有一个视图控制器,我添加了一个观察者喜欢这样

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContent:) name:kTPSShowContentNotification object:self];

其中对象设置为self。我认为这意味着它仅在从该对象发送时才从该通知中查找。我错了吗?

在代码的其他地方我正在发布这样的通知

 [[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:currentVC];

其中 currentVC 是最初设置观察者的视图控制器。我认为这就是捕获该通知所需的全部内容,因为该帖子告诉通知中心从该视图控制器发送它。但它没有抓住它,我不确定为什么。如果在添加观察者时我将对象设置为 nil,那么它会捕获它,但所有其他视图控制器(如果有)也具有该通知的观察者。有没有办法解决 ?我接近这个完全错误吗?

4

2 回答 2

2

要仅从 ObjectSendingNotification 对象接收通知,您应该编写:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContent:) name:kTPSShowContentNotification object:theObjectSendingNotification];

并且对象发送通知应该以这种方式发送

 [[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:self];
于 2012-05-30T11:38:49.263 回答
1

如果我做对了,您想发布并从同一个控制器获得通知。所以你可以做这样的事情:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showContent:) name:kTPSShowContentNotification object:self];

 [[NSNotificationCenter defaultCenter] postNotificationName:kTPSShowContentNotification object:self];

但如果你的currentVCivar 指向同一个控制器,它应该确实有效。你说它不起作用的事实让我相信它没有指向你的控制器的同一个实例。

于 2012-05-30T11:39:15.327 回答