異なるクラスにオブザーバーを追加したい場合、通知センターの使用方法を誰かが説明できますか? 例: classA に通知を投稿します。次に、2 つのオブザーバーを追加します。1 つは classB に、もう 1 つは classC にあり、どちらも同じ通知を待っています。
NSNotificationCenter を使用して、このような通知を送受信できることを理解しています。これを達成するには、各クラスに何を追加する必要がありますか?
異なるクラスにオブザーバーを追加したい場合、通知センターの使用方法を誰かが説明できますか? 例: classA に通知を投稿します。次に、2 つのオブザーバーを追加します。1 つは classB に、もう 1 つは 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];
また、詳細については、Apple の NSNotificationCenter のドキュメントを参照してください。
だから問題は何ですか?それらをすべて追加するだけです。それが通知の優れた点です。通知が投稿されると、各オブザーバーは独自のセレクターを実行します。それでおしまい