发布通知,包括发送者和对象。

3

我似乎找不到如何使用对象和发送者发布通知的方法。

我可以使用名称、发送者和用户信息发布通知。例如:

- (void)postNotificationName:(NSString *)notificationName
                      object:(id)notificationSender
                    userInfo:(NSDictionary *)userInfo

我可以使用一个对象发布NSNotification,但无法将发送者链接到它:

NSNotification *notification = [NSNotification notificationWithName:name
                                                             object:someObject];
[[NSNotificationCenter defaultCenter] postNotification:notification];

有人能告诉我如何使用(a)对象和(b)发送方引用发布通知吗?

1个回答

16
在你提供的两种方法中,object变量都代表通知的发送者,可以是任何你想要的东西。如果想要在通知中提供额外的对象,可以将带有你的对象的字典传递给userInfo
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                      someObject, @"someObject",
                                      anotherObject, @"anotherObject", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:name
                                                    object:sender
                                                  userInfo:options];

我正在考虑这个解决方案,但我希望有一个更通用的解决方案,而不是键值对。但现在它可以使用。谢谢。 - Mats Stijlaart
1
这是不可能使用 NSNotification API 实现的。这实际上是通用解决方案,它们使提供额外数量的对象成为可能。 - Joost
泛型意味着您必须为提供的对象提供一个键。当只向NSNotification添加一个对象时,项目中的其他类将不必知道使用了什么键,因为没有使用。但感谢您的回答。 - Mats Stijlaart

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接