50

I am trying to send some data using NSNotification but get stuck. Here is my code:

// Posting Notification
NSDictionary *orientationData;
if(iFromInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
    orientationData = [NSDictionary dictionaryWithObject:@"Right"
                                                  forKey:@"Orientation"];
}

NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter postNotificationName:@"Abhinav"
                                  object:nil
                                userInfo:orientationData];

// Adding observer
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(orientationChanged)
                                             name:@"Abhinav"
                                           object:nil];

Now how to fetch this userInfo dictionary in my selector orientationChanged?

Georg Schölly
  • 124,188
  • 49
  • 220
  • 267
Abhinav
  • 37,684
  • 43
  • 191
  • 309

4 Answers4

97

You get an NSNotification object passed to your function. This includes the name, object and user info that you provided to the NSNotificationCenter.

- (void)orientationChanged:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
}
JustSid
  • 25,168
  • 7
  • 79
  • 97
  • Ok. And how to do this? Is it like: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:self) name:@"Abhinav" object:nil];? – Abhinav Oct 05 '10 at 07:19
  • 4
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"Abhinav" object:nil]; – JustSid Oct 05 '10 at 07:21
  • Any reason why one may be ending up with a nil dictionary? – NYC Tech Engineer Nov 10 '14 at 06:05
  • @NYCTechEngineer Because no user info has been provided – JustSid Nov 10 '14 at 07:49
  • @JustSid That's what I thought, but I ran the debugger, and saw that a dictionary was being passed as a parameter during the post. But on the receiving method, when I try to extract userInfo, nothing. – NYC Tech Engineer Nov 10 '14 at 08:31
23

Your selector must have : to accept parameters.
e.g.

@selector(orientationChanged:)

then in the method declaration it can accept the NSNotification parameter.

Navnath Godse
  • 2,233
  • 2
  • 23
  • 32
Manny
  • 6,277
  • 3
  • 31
  • 45
6

You are posting the notification correctly. Please modify the Notification Observer like following.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:)
 name:@"Abhinav" object:nil];

- (void)orientationChanged:(NSNotification *)notification
{
    NSDictionary *dict = [notification userInfo];
}

I hope, this solution will work for you..

Amit Singh
  • 2,644
  • 21
  • 20
0

In swift To get userinfo object

     let dict = notification.userInfo
     print(dict)
amisha.beladiya
  • 363
  • 1
  • 12