Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

[[NSNotificationCenter defaultCenter]
  addObserver:self
     selector:@selector(willAnimateRotationToInterfaceOrientation:toInterfaceOrientation:duration)
         name:@"willAnimateRotationToInterfaceOrientation"
       object:nil];

[[NSNotificationCenter defaultCenter] 
  postNotificationName:@"willAnimateRotationToInterfaceOrientation"
                object:self];
like image 810
Dmitry Avatar asked Apr 11 '13 19:04

Dmitry


2 Answers

Use postNotificationName:object:userInfo: and bundle any parameter you wish to pass inside 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 passed, by doing:

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

To summarize what seen above, the selector used to handle a notification takes one optional parameter of type NSNotification and you can store any information you'd like to pass around inside the userInfo dictionary.

like image 200
Gabriele Petronella Avatar answered Oct 04 '22 03:10

Gabriele Petronella


This doesn't work the way you think it does. A notification message call has one optional parameter, which is an NSNotification object:

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

The notification object has a property, userInfo, which is a dictionary that can be used to pass relevant information. But you can't register arbitrary selectors to be called by the notification center. You pass that dictionary with the notification by using -postNotificationName:object:userInfo: instead of -postNotificationName:object:; the userInfo parameter is just an NSDictionary that you create.

like image 23
Seamus Campbell Avatar answered Oct 04 '22 01:10

Seamus Campbell