web-dev-qa-db-fra.com

Exemple de notification personnalisée Cocoa

Quelqu'un peut-il me montrer un exemple d'objet Cocoa Obj-C, avec une notification personnalisée, comment le déclencher, y souscrire et le gérer?

66
mattdwen
@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];

Pour plus d'informations, consultez la documentation de NSNotificationCenter .

81
Jason Coco

Étape 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");
}

Étape 2:

//trigger event
[[NSNotificationCenter defaultCenter]
    postNotificationName:@"eventType"
    object:nil ];
45
mracoker

Assurez-vous de désenregistrer la notification (observateur) lorsque votre objet est désalloué. Apple indique: "Avant qu'un objet qui observe des notifications soit désalloué, il doit dire au centre de notifications de cesser de lui envoyer des notifications").

Pour les notifications locales, le code suivant s'applique:

[[NSNotificationCenter defaultCenter] removeObserver:self];

Et pour les observateurs de notifications distribuées:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
5
Grigori A.