Iphone (NSNotificationCenter)如何在不同的类中添加观察者?

Iphone (NSNotificationCenter)如何在不同的类中添加观察者?,iphone,ios,objective-c,nsnotificationcenter,Iphone,Ios,Objective C,Nsnotificationcenter,如果我想在不同的类中添加观察者,有人能解释一下如何使用notification center吗?例如:在classA中发布通知。然后,添加两个观察者,一个在classB中,另一个在classC中,都在等待相同的通知 我知道我可以使用NSNotificationCenter发送和接收这样的通知。为了实现这一点,我需要在每个类中添加哪些内容?那么问题是什么?你只要把它们全部加起来。这是通知最酷的地方。发布通知后,每个观察者将执行自己的选择器。这就是notificationCenter的用途:它本质上

如果我想在不同的类中添加观察者,有人能解释一下如何使用notification center吗?例如:在classA中发布通知。然后,添加两个观察者,一个在classB中,另一个在classC中,都在等待相同的通知


我知道我可以使用NSNotificationCenter发送和接收这样的通知。为了实现这一点,我需要在每个类中添加哪些内容?

那么问题是什么?你只要把它们全部加起来。这是通知最酷的地方。发布通知后,每个观察者将执行自己的选择器。这就是notificationCenter的用途:它本质上是一个公告板,在这里,学生可以发布其他学生可能感兴趣的内容,而不必知道他们(或者关心是否有人真的感兴趣)

因此,一个有有趣内容的班级(你的问题中的a类)只需在中央公告栏上发布一条通知:

//Construct the Notification
NSNotification *myNotification = [NSNotification notificationWithName:@"SomethingInterestingDidHappenNotification"
                                                               object:self //object is usually the object posting the notification
                                                             userInfo:nil]; //userInfo is an optional dictionary

//Post it to the default notification center
[[NSNotificationCenter defaultCenter] postNotification:myNotification];
在每个有兴趣获得通知的类(问题中的类B和类C)中,您只需将自己添加为默认通知中心的观察者:

[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@SEL(methodYouWantToInvoke:) //note the ":" - should take an NSNotification as parameter
                                             name:@"SomethingInterestingDidHappenNotification" 
                                           object:objectOfNotification]; //if you specify nil for object, you get all the notifications with the matching name, regardless of who sent them
您还可以在类B和C中实现上面的
@SEL()
部分中指定的方法。一个简单的示例如下所示:

//The method that gets called when a SomethingInterestingDidHappenNotification has been posted by an object you observe for
- (void)methodYouWantToInvoke:(NSNotification *)notification
{
    NSLog(@"Reacting to notification %@ from object %@ with userInfo %@", notification, notification.object, notification.userInfo);
    //Implement your own logic here
}

要发送通知,您需要呼叫

[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationName" object:nil];
要收到通知,您需要致电

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(methodNameToCallWhenNotified)
                                                 name:@"NotificationName"
                                               object:nil];
然后,要将该类作为观察者删除,可以使用

[[NSNotificationCenter defaultCenter] removeObserver:self];

另外,请参阅了解详细信息。

苹果可以很好地解释这一点:嗨,安德烈,问题是下一个问题:我有3门课,在classA是我发布通知的地方;在classB中,我添加了一个观察者(这个观察者工作正常);在classC中,我正在以与classB相同的方式添加一个新的方法(两个都响应相同的通知字符串),但在日志文件中,我看到只有classB observer被触发。因此,在类接口中,我不必编写任何代码。对不起,我是这方面的新手。我不确定我是否正确理解了您的问题。您不必声明任何新方法(除了对B类和C类中传入的通知做出反应的通知)。Thansk!我上周五修复了它。