使用NSNotificationCenter在VC之间发送数据

时间:2013-03-24 15:08:14

标签: ios objective-c uiviewcontroller nsnotificationcenter nsnotification

我需要使用NSMutableDictionaryViewControllerA从一个班级ViewControllerB传递到另一个班级(NSNotificationCenter)。我尝试了以下代码,但它不起作用。我实际上传递给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];
}

1 个答案:

答案 0 :(得分:2)

您对NSNotificationCenter方法的调用很好。需要考虑的一些事项:

  1. ViewControllerB个实例在调用-viewWillAppear:之前不会注册通知,因此如果您尚未显示ViewControllerB的实例(通常情况下,如果它在VC层次结构中比A)更远,则无法获得通知调用。在-initWithNibName:bundle:注册通知更有可能是您想要的。

  2. 其必然结果是:当您发送通知以便收到通知时,您的ViewControllerB实例必须存在。如果您从ViewControllerB MainStoryboard加载-nextView:,则表示尚未注册该通知。