开发者

Determine which object posted a notification?

I'm having trouble identifying how to tell which object posted a notification.

I subscribe to a notification in object A:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receivedNotification:) name=@"ReceivedData" object:nil]

I post a notification from object B:

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

I recieve the notification in object A:

- (void) receivedNotification: (NSNotification*) notification
{
   // Method is hit fine, notification object contains data.
}

How can I tell that it was object B that sent the data and not, for instance, a object C? 开发者_如何转开发 I need a reference to the sender. I don't want to add the sender to the notification object being passed, as I am specifiying the sender when I call the notification in object B


The NSNotification class has a method called object that returns the object associated with the notification. This is often the object that posted this notification.

- (void) receivedNotification: (NSNotification*) notification
{
   ...
   id myObject = [notification object];
   ...
}


If you only want to handle notifications from Class B, then you specify that as the object (which you have left as nil) when subscribing to the notification.

With the nil, you receive notifications from all objects that post that specific notification.

edit

You call [notification object] to know what object posted the notification.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜