2011-07-19 25 views
20

Tengo un NSNotification que está publicando un NSDictionary:objeto de acceso pasado en NSNotification?

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: 
              anItemID, @"ItemID", 
              [NSString stringWithFormat:@"%i",q], @"Quantity", 
              [NSString stringWithFormat:@"%@",[NSDate date]], @"BackOrderDate", 
              [NSString stringWithFormat:@"%@", [NSDate date]],@"ModifiedOn", 
              nil]; 

        [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:@"InventoryUpdate" object:dict]]; 

¿Cómo me suscribo a esto y obtener información de este NSDictionary?

en mi viewDidLoad que tengo:

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

y un método en la clase:

- (void)recieveInventoryUpdate:(NSNotification *)notification { 
    NSLog(@"%@ updated", [notification userInfo]); 
} 

que registra un valor nulo, por supuesto.

+0

[versión Swift] (http://stackoverflow.com/a/42180596/1634890) –

Respuesta

32

es [notification object]

también puede enviar userinfo utilizando notificationWithName:object:userInfo: método

+8

objeto no es la intención de ser una forma de almacenar los datos transmitidos con la notificación.Está destinado a ser el remitente de la notificación, de esa manera usted puede averiguar qué tipo de objeto envió la notificación y actuar en consecuencia. Usando 'notificationWithName: object: userInfo:' es el camino a seguir aquí. – ColdLogic

2

Usted lo está haciendo mal. Necesita utilizar:

-(id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfo 

y pasar el dict al último parámetro. Su parámetro "objeto" es el objeto que envía la notificación y no el diccionario.

13

El objeto es qué objeto está publicando la notificación, no es una forma de almacenar el objeto para poder acceder a él. La información del usuario es donde almacena la información que desea conservar con la notificación.

[[NSNotificationCenter defaultCenter] postNotificationName:@"Inventory Update" object:self userInfo:dict]; 

Luego regístrese para la notificación. El objeto puede ser su clase o nula a solo recibir todas las notificaciones de este nombre

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

Siguiente utilizarlo en su selector de

- (void)recieveInventoryUpdate:(NSNotification *)notification { 
    NSLog(@"%@ updated", [notification userInfo]); 
} 
0

la object partir de la notificación está destinada a ser la emisor , en su caso, el diccionario no es realmente el emisor, es solo información. Cualquier información auxiliar que se envíe junto con la notificación se debe pasar junto con el diccionario userInfo. Enviar la notificación como tal:

NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: 
             anItemID, 
             @"ItemID", 
             [NSString stringWithFormat:@"%i",q], 
             @"Quantity", 
             [NSString stringWithFormat:@"%@", [NSDate date]], 
             @"BackOrderDate", 
             [NSString stringWithFormat:@"%@", [NSDate date]], 
             @"ModifiedOn", 
             nil]; 

[[NSNotificationCenter defaultCenter] postNotification: 
     [NSNotification notificationWithName:@"InventoryUpdate" 
             object:self 
            userInfo:dict]]; 

Y luego recibirlo como este, para obtener el comportamiento que la intención en el buen sentido:

- (void)recieveInventoryUpdate:(NSNotification *)notification { 
    NSLog(@"%@ updated", [notification userInfo]); 
} 
+0

Necesita registrarse para la notificación. Solo un pequeño detalle que dejaste fuera: P – ColdLogic

+0

@ColdLogic: cierto. Intencionalmente lo dejé por brevedad, ya que la pregunta original ya contenía esa información, estoy seguro de que Slee ya entiende eso :). – PeyloW

+0

se sorprendería;) – ColdLogic

2

Es muy sencillo, véase más adelante

- (void)recieveInventoryUpdate:(NSNotification *)notification { 
    NSLog(@"%@ updated",notification.object); // gives your dictionary 
    NSLog(@"%@ updated",notification.name); // gives keyname of notification 

} 

si tiene acceso al notification.userinfo, devolverá null.

+0

Gracias. Me funcionó increíble.! – Raja

0

Swift:

// Propagate notification: 
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: ["info":"your dictionary"]) 

// Subscribe to notification: 
NotificationCenter.default.addObserver(self, selector: #selector(yourSelector(notification:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil) 

// Your selector: 
func yourSelector(notification: NSNotification) { 
    if let info = notification.userInfo, let infoDescription = info["info"] as? String { 
      print(infoDescription) 
     } 
} 

// Memory cleaning, add this to the subscribed observer class: 
deinit { 
    NotificationCenter.default.removeObserver(self) 
} 
Cuestiones relacionadas