Подтвердить что ты не робот

Объект доступа, переданный в 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?

в моем представленииDidLoad У меня есть:

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

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

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

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

4b9b3361

Ответ 1

it [notification object]

вы также можете отправить userinfo с помощью метода notificationWithName:object:userInfo:

Ответ 2

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

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

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

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

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

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

Ответ 3

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

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

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

Ответ 4

Это просто, см. ниже

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

}

если доступ к notification.userinfo, он вернет null.

Ответ 5

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

Ответ 6

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)
}