Exemple de notification personnalisée de cacao
-
20-08-2019 - |
Question
Quelqu'un peut-il me montrer un exemple d'objet Cocoa Obj-C, avec une notification personnalisée, comment l'activer, s'y abonner et le gérer?
La solution
@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 .
Autres conseils
É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 ];
Assurez-vous de désenregistrer la notification (observateur) lorsque votre objet est désalloué. La documentation Apple indique: & "Avant qu'un objet observant des notifications ne soit désalloué, il doit dire au centre de notifications de ne plus envoyer de notifications &";
Pour les notifications locales, le code suivant est applicable:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Et pour les observateurs des notifications distribuées:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow