объект доступа передан в NSNotification?

У меня есть NSNotification, которое публикует NSDictionary:

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

Как мне подписаться на это и получить информацию из этого NSDictionary?

в моем viewDidLoad у меня есть:

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

и метод в классе:

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

, который регистрирует конечно, нулевое значение.

23
задан IPS Brar 13 April 2017 в 14:30
поделиться

4 ответа

Объект - это то, что объект публикует уведомление, а не способ сохранить объект, чтобы вы могли получить к нему доступ. Информация о пользователе - это место, где вы храните информацию, которую хотите сохранить с уведомлением.

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

Затем зарегистрируйтесь для уведомления. Объектом может быть ваш класс или ноль, чтобы просто получать все уведомления с этим именем

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

Далее используйте его в своем селекторе

- (void)recieveInventoryUpdate:(NSNotification *)notification {
    NSLog(@"%@ updated", [notification userInfo]);
}
14
ответ дан 29 November 2019 в 01:24
поделиться

Вы делаете это неправильно. Вам нужно использовать:

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

и передать dict последнему параметру. Ваш параметр "object" - это объект, отправляющий уведомление, а не словарь.

2
ответ дан 29 November 2019 в 01:24
поделиться

object из уведомления предназначено быть отправителем , в вашем случае словарь на самом деле не является отправителем , это просто информация. Любая вспомогательная информация, которая будет отправлена ​​вместе с уведомлением, предназначена для передачи вместе со словарем userInfo. Отправьте уведомление следующим образом:

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

А затем получите его вот так, чтобы получить правильное поведение, которое вы намереваетесь:

- (void)recieveInventoryUpdate:(NSNotification *)notification {
    NSLog(@"%@ updated", [notification userInfo]);
}
1
ответ дан 29 November 2019 в 01:24
поделиться

Свифт:

// 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)
}
0
ответ дан 29 November 2019 в 01:24
поделиться