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

Jos*_*iaz 0 iphone objective-c nsnotificationcenter ios

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

我知道我可以使用NSNotificationCenter发送和接收这样的通知.为了实现这一目标,我需要为每个类添加什么?

fzw*_*zwo 6

这正是通知中心所针对的:它本质上是一个公告板,类可以发布其他类可能感兴趣的东西,而不必了解它们(或者关心是否有人真正感兴趣).

所以有一个有趣的课程(你的问题中的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];
Run Code Online (Sandbox Code Playgroud)

在每个有兴趣获得通知的课程中(您的问题中的课程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
Run Code Online (Sandbox Code Playgroud)

您还可以@SEL()在类B和C中实现上面部分中指定的方法.一个简单的示例如下所示:

//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
}
Run Code Online (Sandbox Code Playgroud)