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];
}
Your calls to the NSNotificationCenter
methods are fine. A few things to consider:
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.
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.