69

カスタム通知を含む Cocoa Obj-C オブジェクトの例、それを起動する方法、サブスクライブする方法、および処理する方法を教えてください。

4

3 に答える 3

82
@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のドキュメントを参照してください。

于 2009-05-09T05:25:07.307 に答える
45

ステップ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 ];
于 2010-06-22T13:26:41.050 に答える
6

オブジェクトの割り当てが解除されたら、必ず通知 (オブザーバー) を登録解除してください。Apple のドキュメントには次のように記載されています。

ローカル通知の場合、次のコードが適用されます。

[[NSNotificationCenter defaultCenter] removeObserver:self];

配布された通知のオブザーバーの場合:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
于 2012-12-10T16:18:22.997 に答える