ios – 使用NSNotificationCenter在VC之间发送数据

我需要使用NSNotificationCenter将NSMutableDictionary从一个类(ViewControllerA)传递到另一个类(ViewControllerB).我尝试了以下代码,但它不起作用.我实际上传递给ViewControllerB但是没有调用-receiveData方法.有什么建议吗?谢谢!

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];
}

最佳答案 您对NSNotificationCenter方法的调用很好.需要考虑的一些事项:

> ViewControllerB实例在调用-viewWillAppear:之前不会注册通知,所以如果你还没有显示ViewControllerB的实例(通常,如果它比VC的层次结构还要远远超过A),你就不能收到通知电话.在-initWithNibName中注册通知:bundle:更有可能是你想要的.
>其必然结果是:当您发送通知以便接收通知时,您的ViewControllerB实例必须存在.如果您在-nextView中从MainStoryboard加载ViewControllerB,那么它尚未注册通知.

点赞