[英]NSNotification send multiple objects?
I am learning how to use NSNotificationCenter. 我正在学习如何使用NSNotificationCenter。 My understanding is that for each notification, you can send a single object.
我的理解是,对于每个通知,您都可以发送一个对象。 Is there a way to send a notification with multiple objects or must I post a new notification for each object?
有没有一种发送带有多个对象的通知的方法,或者我必须为每个对象发布新的通知吗?
You can pass any information you like in the userInfo
argument of postNotification:object:userInfo:
. 您可以在
postNotification:object:userInfo:
的userInfo
参数中传递您喜欢的任何信息。
For example, you could call the method as follows: 例如,您可以按以下方式调用方法:
NSDictionary *accountDetails = @{@"accountHolder":@"Mr John Smith",
@"accountNumber":@(01234567),
@"sortCode":@"01-98-34"};
[[NSNotificationCenter defaultCenter] postNotificationName:@"BankDidCreateNewAccount" object:self userInfo:accountDetails];
Just to explain in more detail: to post notifications with an object, you'd use either 只是为了更详细地说明:发布带有对象的通知,您可以使用
-postNotificationName:object:
or -postNotificationName:object:userInfo:
-postNotificationName:object:
或-postNotificationName:object:userInfo:
In the object argument, you may only supply a single object. 在object参数中,您只能提供一个对象。 Typically, the
object
argument is the notificationSender
, ie you would pass self
from wherever you post the notification. 通常,
object
参数是notificationSender
,即无论您在哪里发布notificationSender
,都将传递self
。
If you have registered for notifications using -addObserver:selector:name:object:
, and you passed any value but nil
for the object
argument, then you will only receive notifications where the posted notification object ( object
argument in -postNotificationName:object:
) matches the the object
argument in -addObserver:
. 如果您已使用
-addObserver:selector:name:object:
注册了通知,并且为object
参数传递了除nil
任何值,那么您将仅收到发布的通知对象的通知( -postNotificationName:object:
object
参数)与-addObserver:
的object
参数匹配。
If you pass nil
in -addObserver:
then the object
value of -postNotification:
is ignored for this particular observer. 如果传递
nil
在-addObserver:
那么object
的值-postNotification:
为这一特定的观察者忽略。
Wow, that sounds complicated. 哇,听起来很复杂。 But it's actually very simple.
但这实际上非常简单。
object
argument must match if used in -addObserver:
. 如果在
-addObserver:
使用,则object
参数必须匹配。
Use userInfo
argument to supply more details to the notification observer. 使用
userInfo
参数可向通知观察器提供更多详细信息。
A notification can only have one object
. 一个通知只能有一个
object
。 For multiple objects it depends what you want to send them for. 对于多个对象,这取决于要发送它们的对象。 If each is being observed separately then yes, you need to send multiple notifications.
如果分别观察每个,则是,您需要发送多个通知。 If you just need to send context info then you should use
userInfo
. 如果只需要发送上下文信息,则应该使用
userInfo
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.