2009-05-09 8 views
66

¿Puede alguien mostrarme un ejemplo de un objeto Cocoa Obj-C, con una notificación personalizada, cómo abrirlo, suscribirse y manejarlo?Ejemplo de notificación personalizada de cacao

+4

pregunta Vague. Intente hacer una pregunta más específica o busque la documentación de Apple. – danielpunkass

+6

Normalmente, no comentaría sobre una pregunta como esta, pero al ver cómo recibiste una "estafa", la mía puede ser una "pro". Esta pregunta permite una respuesta * concisa * que trata estrictamente del tema. Simplemente quiero encontrar una cosa simple: no la documentación de * scour * apple (que de todos modos valdría la pena). Así que gracias por hacer esta pregunta. Veo tu +15 atm en la pregunta que es congruente con mi opinión. – Jacksonkr

+1

+1 también. Gracias. –

Respuesta

80
@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.

+0

¿De qué sirve usar la notificación? ¿Por qué no simplemente llamar a [object handleNotification] directamente? –

+3

Acoplamiento flojo. Observe el comentario "// en otro lugar" ... La notificación es un tipo de mensaje de difusión. Cualquier instancia de objeto puede escuchar una notificación y no necesita ajustarse a ningún protocolo de delegado particular o similar. Puede haber muchas instancias escuchando un solo mensaje. El remitente no necesita tener punteros a la (s) instancia (s) de objeto que desea notificar. –

45

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 ]; 
+0

Oh, muchas gracias por un buen ejemplo. Esto es exactamente lo que necesito. – d12frosted

+0

Gorgeous :) Muchas gracias –

5

Asegúrese de anular el registro de la notificación (observador) cuando se cancela la asignación de su objeto. La documentación de Apple establece: "Antes de desasignar un objeto que está observando notificaciones, debe decirle al centro de notificaciones que deje de enviarle notificaciones".

para las notificaciones locales con el siguiente código es aplicable:

[[NSNotificationCenter defaultCenter] removeObserver:self]; 

Y para los observadores de las notificaciones distribuidas:

[[NSDistributedNotificationCenter defaultCenter] removeObserver:self]; 
Cuestiones relacionadas