Ejemplo de notificación personalizada de cacao
-
20-08-2019 - |
Pregunta
¿Puede alguien mostrarme un ejemplo de un objeto Cocoa Obj-C, con una notificación personalizada, cómo dispararlo, suscribirse y manejarlo?
Solución
@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];
Para obtener más información, consulte la documentación de NSNotificationCenter .
Otros consejos
Paso 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");
}
Paso 2:
//trigger event
[[NSNotificationCenter defaultCenter]
postNotificationName:@"eventType"
object:nil ];
Asegúrese de anular el registro de la notificación (observador) cuando su objeto se desasigna. La documentación de Apple dice: & Quot; Antes de que un objeto que está observando notificaciones se desasigne, debe indicarle al centro de notificaciones que deje de enviar notificaciones & Quot ;.
Para notificaciones locales se aplica el siguiente código:
[[NSNotificationCenter defaultCenter] removeObserver:self];
Y para los observadores de notificaciones distribuidas:
[[NSDistributedNotificationCenter defaultCenter] removeObserver:self];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow