2

我无法在 NSNotificationCenter 中执行选择器方法 receiveChatText,我想知道问题是否是因为 NSNotification postNotificationName 在 AppDelegate.m 中但 NSNotificationCenter 在 ViewController.m 中?IE 可以 postNotificationName 知道 NSNotificationCenter 在另一个 viewController 文件中还是我需要告诉它的东西?

在 viewController.m 我有

 -(id)init
 {
self = [super init];
if(self){
    [[NSNotificationCenter defaultCenter] addObserver:self  
                                      selector:@selector(receiveChatText:) 
                                                      name:ChatMessageReceived  
                                               object:nil];
 return self;
}

- (void)receiveChatText:(NSNotification *)note {
NSLog(@"received chat text");

}

在顶级 AppDelegate.m 文件中,我有以下内容:

 -(void) didReceiveMessage {
    [[NSNotificationCenter defaultCenter] postNotificationName:ChatMessageReceived 
                                          object:nil
                                          userInfo:nil];        
 }

有什么想法可以阻止在调用 didReceiveMessage 时执行 receiveChatText 吗?

4

3 回答 3

1

我无法获取选择器方法,receiveChatText,...</p>

首先,它是receiveChatText:, 带有冒号。这在 Objective-C 中很重要——<code>receiveChatText: 并且receiveChatText不要引用相同的方法。

其次,“选择器”并不意味着你认为它的意思。选择器是方法的名称。您将选择器传递给您希望通知中心发送给观察者的消息。也就是说,你告诉通知中心“当这个通知到达时,给receiveChatText:我[视图控制器]发送一条消息”。

… 在 NSNotificationCenter 中…</p>

通知中心没有receiveChatText:方法。您的观察者 ( self) 会这样做,这就是您希望通知中心向其发送消息的原因。

…执行,我想知道问题是否是因为 NSNotification postNotificationName 在 AppDelegate.m 中…</p>

AppDelegate.m 中没有这样的东西。

应用程序委托发布通知。

…但是 NSNotificationCenter 在 ViewController.m 中?

ViewController.m 中没有这样的东西。

视图控制器观察通知。

只要视图控制器在应用程序委托发布通知之前将自己添加为观察者,这将起作用。如果它不起作用,则任何一个或两个步骤都没有发生,或者它们以错误的顺序发生。

IE 可以 postNotificationName 知道 NSNotificationCenter 在另一个 viewController 文件中还是我需要告诉它的东西?

通知中心不在这两个文件中。[NSNotificationCenter defaultCenter]是一个单例对象,在整个应用程序中共享给任何想要使用它的对象。这就是您可以使用它来让应用程序委托与视图控制器和任何其他正在观察通知的对象进行通信的方式。

您正在向默认通知中心发送一条postNotificationName:object:userInfo:消息。这是您之前应该发送addObserver:selector:name:object:消息的默认通知中心。只要您先开始观察,然后将通知发送到同一个通知中心,通知中心就可以将通知分派给您添加的观察者。

任何可以阻止 receiveChatText 的想法

receiveChatText:

从调用 didReceiveMessage 时执行?

  1. didReceiveMessage没有发布通知。假设您在问题中显示的代码是准确的,情况并非如此。
  2. 视图控制器没有观察通知。既然它开始观察创造,也许它还没有被创造。或者,可能是因为您已经覆盖init而不是 NS/UIViewController 的initWithNibName:bundle:. 注意不同类的指定初始化器是什么;文档通常会说。
  3. 视图控制器尚未观察通知:您在视图控制器开始观察通知之前发布了通知(即,在您创建视图控制器之前)。

You might also want to pass the chat text as the object of the notification, or in its userInfo, rather than forcing all observers of the notification to retrieve it from an unspecified source.

于 2011-01-02T11:13:48.587 回答
0

+defaultCenter 是 NSNotificationCenter 上的一个类方法,无论您从哪里调用它,每次在给定进程中调用它时都会返回相同的 NSNotificationCenter 实例。

'ChatMessageReceived' 是如何定义的?它应该是一个 NSString,但名称“ChatMessageReceived”在你的两个类的上下文中是一个有效的符号吗?

于 2011-01-02T07:49:44.567 回答
0

看起来它应该可以工作,只要ChatMessageReceived两个实例中的值相同。

你有没有使用调试器验证在通知发布到 didReceiveMessage之前init调用了视图控制器文件中的方法?

于 2011-01-02T07:49:46.237 回答