У меня есть 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]);
}
, который регистрирует конечно, нулевое значение.
Объект - это то, что объект публикует уведомление, а не способ сохранить объект, чтобы вы могли получить к нему доступ. Информация о пользователе - это место, где вы храните информацию, которую хотите сохранить с уведомлением.
[[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]);
}
Вы делаете это неправильно. Вам нужно использовать:
-(id)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)userInfo
и передать dict последнему параметру. Ваш параметр "object" - это объект, отправляющий уведомление, а не словарь.
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]);
}
Свифт:
// 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)
}