在NSNotification中传递的访问对象?

Sle*_*lee 23 objective-c nsnotifications ios

我有一个发布NSDictionary的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]];
Run Code Online (Sandbox Code Playgroud)

我如何订阅此并从此NSDictionary获取信息?

在我的viewDidLoad我有:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recieveInventoryUpdate:) name:@"InventoryUpdate" object:nil];
Run Code Online (Sandbox Code Playgroud)

和班上的方法:

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

当然记录一个空值.

ale*_*x-i 34

它的 [notification object]

您也可以使用notificationWithName:object:userInfo:方法发送userinfo

  • 对象并不意味着存储随通知传递的数据.它意味着成为通知的发送者,这样您就可以找出发送通知的对象类型并采取相应的行动.使用`notificationWithName:object:userInfo:`是这里的方法. (9认同)

Col*_*gic 14

对象是发布通知的对象,而不是存储对象的方法,因此您可以访问它.用户信息是您存储要与通知保持一致的信息的位置.

[[NSNotificationCenter defaultCenter] postNotificationName:@"Inventory Update" object:self userInfo:dict];
Run Code Online (Sandbox Code Playgroud)

然后注册通知.对象可以是您的类,也可以只接收此名称的所有通知

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(recieveInventoryUpdate:) name:@"InventoryUpdate" object:nil];
Run Code Online (Sandbox Code Playgroud)

接下来在选择器中使用它

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