質問

誰かが、それを発射、それに加入し、それをどのように処理するか、カスタムの通知で、私にココアの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];

詳細については、<のhref = "http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/のためのマニュアルを参照してくださいUID / 20000219-2831" のrel = "noreferrer"> NSNotificationCenter を。

他のヒント

ステップ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 ];

あなたのオブジェクトの割り当てが解除されたときに通知(オブザーバー)を登録解除することを確認します。アップルのドキュメントの状態:「通知を観察しているオブジェクトの割り当てが解除される前に、それを通知送信を停止する通知センターに伝えなければなりません」。

ローカル通知のために、次のコードが適用されます:

[[NSNotificationCenter defaultCenter] removeObserver:self];

と分散通知のオブザーバーのために:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top