2010-10-05 9 views
46

Sto tentando di inviare alcuni dati utilizzando NSNotification ma restiamo bloccati. Ecco il mio codice:Come passare userInfo in 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]; 

Ora, come per andare a prendere questo dizionario userInfo nel mio selettore orientationChanged?

risposta

91

Ottieni un oggetto NSNotification passato alla tua funzione. Questo include il nome, l'oggetto e le informazioni utente che hai fornito a NSNotificationCenter.

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

Ok. E come si fa? È come: [[NSNotificationCenter defaultCenter] addObserver: self-selector: @selector (orientationChanged: self) nome: @ oggetto "Abhinav": nil] ;? – Abhinav

+4

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

+0

Qualche motivo per cui si potrebbe finire con un dizionario nil? –

23

Il selettore deve avere : per accettare i parametri.
ad es.

@selector(orientationChanged:) 

quindi nella dichiarazione del metodo può accettare il parametro NSNotification.

5

Si sta postando correttamente la notifica. Si prega di modificare l'osservatore delle notifiche come segue.

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

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

spero, questa soluzione funziona per voi ..

0

a Swift Per ottenere userinfo oggetto

 let dict = notification.userInfo 
    print(dict) 
Problemi correlati