문제

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:

  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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top