How to pass userInfo in NSNotification?

IphoneCocoaCocoa Touch

Iphone Problem Overview


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?

Iphone Solutions


Solution 1 - Iphone

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

Solution 2 - Iphone

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

@selector(orientationChanged:)

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

Solution 3 - Iphone

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..

Solution 4 - Iphone

In swift To get userinfo object

     let dict = notification.userInfo
     print(dict)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAbhinavView Question on Stackoverflow
Solution 1 - IphoneJustSidView Answer on Stackoverflow
Solution 2 - IphoneMannyView Answer on Stackoverflow
Solution 3 - IphoneAmit SinghView Answer on Stackoverflow
Solution 4 - Iphoneamisha.beladiyaView Answer on Stackoverflow