Post notification with sender and object

Mats Stijlaart picture Mats Stijlaart · May 8, 2011 · Viewed 15.5k times · Source

I cannot seem to find out how to post a notification with an object and a sender.

I can post a notification with a name, sender and user info. See:

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

And I can post a NSNotification with an object, but not link an sender to it:

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

Can anybody tell me how to post a notification with (a) a object and (b) a sender reference?

Answer

Joost picture Joost · May 8, 2011

In both methods you propose, the object variable represents the sender of the notification, which can be anything you want really. To provide additional objects with the notification, you could pass a dictionary with your objects to userInfo.

NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                      someObject, @"someObject",
                                      anotherObject, @"anotherObject", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:name
                                                    object:sender
                                                  userInfo:options];