How to send a notification with parameters to Objective-C?

I need to send a notification @"willAnimateRotationToInterfaceOrientation" with the parameters toInterfaceOrientation and duration ( question # 1 ) to all UIViewController in the application ( question # 2 ). How to write code for this?

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willAnimateRotationToInterfaceOrientation:toInterfaceOrientation:duration) name:@"willAnimateRotationToInterfaceOrientation" object:nil]; [[NSNotificationCenter defaultCenter] postNotificationName:@"willAnimateRotationToInterfaceOrientation" object:self]; 
+7
source share
3 answers

Use postNotificationName:object:userInfo: and bind any parameter you want to pass in the userInfo dictionary.

Example:

You can post a notification like this

 NSDictionary * userInfo = @{ @"toOrientation" : @(toOrientation) }; [[NSNotificationCenter defaultCenter] postNotificationName:@"willAnimateRotationToInterfaceOrientation" object:nil userInfo:userInfo]; 

And then retrieve the information you submitted by doing:

 - (void)willAnimateRotationToInterfaceOrientation:(NSNotification *)n { UIInterfaceOrientation toOrientation = (UIInterfaceOrientation)[n.userInfo[@"toOrientation"] intValue]; //.. } 

To summarize what was seen above, the selector used to process notifications accepts one optional parameter of type NSNotification , and you can store any information that you want to skip inside the userInfo dictionary.

+19
source

This does not work the way you think. The notification notification call has one optional parameter, which is an NSNotification object:

 -(void)myNotificationSelector:(NSNotification*)note; -(void)myNotificationSelector; 

The notification object has the userInfo property, which is a dictionary that can be used to convey relevant information. But you cannot register arbitrary selectors that will be called by the notification center. You pass this dictionary with a notification using -postNotificationName:object:userInfo: instead of -postNotificationName:object: the userInfo parameter is just the NSDictionary you are creating.

+1
source

You create an easier way to call that takes fewer arguments and makes a complex call for you.

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doStuff) name:@"willAnimateRotationToInterfaceOrientation" object:nil]; - (void)doStuff { [self willAnimateRotationToInterfaceOrientation:someOrientation toOrientation:someOtherOrientation duration:1]; } 

You should not call willAnimateRotationToInterfaceOrientation: . Instead, create a method that is called by a form that contains the code that you want to activate on rotation, as well as other times.

0
source

All Articles