Search code examples
objective-cobjectnotificationssender

Post notification with sender and object


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?


Solution

  • 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];