誰かに、カスタム通知、発射方法、購読方法、および処理方法を示すCocoa Obj-Cオブジェクトの例を表示できますか?ココアのカスタム通知の例
答えて
@implementation MyObject
// Posts a MyNotification message whenever called
- (void)notify {
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyNotification" object:self];
}
// Prints a message whenever a MyNotification is received
- (void)handleNotification:(NSNotification*)note {
NSLog(@"Got notified: %@", note);
}
@end
// somewhere else
MyObject *object = [[MyObject alloc] init];
// receive MyNotification events from any object
[[NSNotificationCenter defaultCenter] addObserver:object selector:@selector(handleNotification:) name:@"MyNotification" object:nil];
// create a notification
[object notify];
詳細については、NSNotificationCenterのマニュアルを参照してください。
通知を使用するポイントは何ですか?単に[object handleNotification]をまっすぐに呼び出さないのはなぜですか? –
緩いカップリング。 "// somewhere else"コメントに注意してください。通知は一種のブロードキャストメッセージです。どんなオブジェクトインスタンスも通知を聞くことができ、特定のデリゲートプロトコルなどに準拠する必要はありません。単一のメッセージを聞いているインスタンスがたくさんあるかもしれません。送信者は、通知したいオブジェクトインスタンスへのポインタを持つ必要はありません。 –
ステップ1:
//register to listen for event
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(eventHandler:)
name:@"eventType"
object:nil ];
//event handler when event occurs
-(void)eventHandler: (NSNotification *) notification
{
NSLog(@"event triggered");
}
ステップ2:
//trigger event
[[NSNotificationCenter defaultCenter]
postNotificationName:@"eventType"
object:nil ];
ああ、本当にありがとうございます。これは私が必要とするものです。 – d12frosted
ゴージャス:)おかげでたくさん –
あなたのオブジェクトの割り当てが解除されたときに通知(オブザーバー)を登録解除することを確認します。アップルのドキュメントでは、「通知を監視しているオブジェクトが割り当て解除される前に、通知センターに通知の送信を停止するよう指示する必要があります。ローカル通知用の
次のコードが適用されます。
[[NSNotificationCenter defaultCenter] removeObserver:self];
と分散通知のオブザーバーのために:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
漠然とした質問です。より具体的な質問をするか、Appleのマニュアルを検索してみてください。 – danielpunkass
私は通常、このような質問にはコメントしませんが、あなたが "con"を受け取った方法を見て、その後私のものは "pro"になることがあります。この質問は、トピックと厳密に対処する*簡潔な答えを可能にします。私は単なる単純なことを見つけたいだけです。* apple *のドキュメントを調べるのではなく、おそらく価値があります。この質問をしてくれてありがとう。私はあなたの+15気圧が私の感情と一致しているのを見ます。 – Jacksonkr
+1もあります。ありがとう。 –