2010-10-05 17 views
46

Estoy tratando de enviar algunos datos usando NSNotification pero me atoco. Aquí está mi código:¿Cómo pasar userInfo en NSNotification?

// Posting Notification 
NSDictionary *orientationData; 
if(iFromInterfaceOrientation == UIInterfaceOrientationLandscapeRight) { 
    orientationData = [NSDictionary dictionaryWithObject:@"Right" 
                forKey:@"Orientation"]; 
} 

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; 
[notificationCenter postNotificationName:@"Abhinav" 
            object:nil 
           userInfo:orientationData]; 

// Adding observer 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(orientationChanged) 
              name:@"Abhinav" 
              object:nil]; 

Ahora, ¿cómo se ha podido recuperar este diccionario userInfo en mi selector de orientationChanged?

Respuesta

91

Obtiene un objeto NSNotification pasado a su función. Esto incluye el nombre, el objeto y la información del usuario que proporcionó a NSNotificationCenter.

- (void)orientationChanged:(NSNotification *)notification 
{ 
    NSDictionary *dict = [notification userInfo]; 
} 
+0

Ok. ¿Y cómo hacer esto? ¿Es como: [[NSNotificationCenter defaultCenter] addObserver: auto selector: @selector (orientationChanged: self) name: @ "Abhinav" object: nil] ;? – Abhinav

+4

[[NSNotificationCenter defaultCenter] addObserver: selector automático: @selector (orientationChanged :) name: @ "Abhinav" object: nil]; – JustSid

+0

¿Alguna razón por la cual uno puede estar terminando con un diccionario nulo? –

23

Su selector debe tener : a aceptar parámetros.
p.

@selector(orientationChanged:) 

entonces en la declaración de método que puede aceptar el parámetro NSNotification.

5

Está publicando la notificación correctamente. Modifique el observador de notificaciones de la siguiente manera.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) 
name:@"Abhinav" object:nil]; 

- (void)orientationChanged:(NSNotification *)notification 
{ 
    NSDictionary *dict = [notification userInfo]; 
} 

espero, esta solución va a funcionar para usted ..

0

en Swift Para obtener userinfo objeto

 let dict = notification.userInfo 
    print(dict) 
Cuestiones relacionadas