4

I need to pass a NSMutableDictionary from one class (ViewControllerA) to another (ViewControllerB) using NSNotificationCenter. I have tried the following code but it doesn't work. I actually pass to the ViewControllerB but the -receiveData method isn't called. Any suggestion? Thanks!

ViewControllerA.m

- (IBAction)nextView:(id)sender {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"PassData"
     object:nil
     userInfo:myMutableDictionary];
    UIViewController *viewController =
    [[UIStoryboard storyboardWithName:@"MainStoryboard"
                               bundle:NULL] instantiateViewControllerWithIdentifier:@"viewcontrollerb"];
    [self presentViewController:viewController animated:YES completion:nil];
}

ViewControllerB.m

- (void)receiveData:(NSNotification *)notification {
    NSLog(@"Data received: %@", [notification userInfo]);
}

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(receiveData:)
     name:@"PassData"
     object:nil];
}
IOS_DEV
  • 949
  • 3
  • 12
  • 33
  • 1
    Why are you using notifications in this case? Normally, notifications are used when you need to broadcast an event (possibly with additional data) and the broadcaster doesn't care who or how many other classes are interested in the event. In this case, it seems your only need is to ensure that ViewControllerA passes some data to ViewControllerB and only at the time that VCA creates and displays VCB. Why not simply have VCA set a property on VCB instead of using a notification? – rmaddy Mar 24 '13 at 15:50

1 Answers1

2

Your calls to the NSNotificationCenter methods are fine. A few things to consider:

  1. ViewControllerB instances won't register for the notification until -viewWillAppear: has been called on them, so if you haven't shown your instance of ViewControllerB yet (typically, if it's farther down the VC hierarchy than A), you can't get the notification call. Registering for notifications in -initWithNibName:bundle: is more likely to be what you want.

  2. A corollary of that is: your instance of ViewControllerB must exist when you send the notification in order for it to be received. If you are loading ViewControllerB from MainStoryboard in -nextView:, then it hasn't registered for the notification yet.

Seamus Campbell
  • 17,816
  • 3
  • 52
  • 60