我需要使用 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];
}

最佳答案

您对 NSNotificationCenter 方法的调用很好。需要考虑的几点:

  • ViewControllerB 实例在 -viewWillAppear: 被调用之前不会注册通知,所以如果你还没有显示你的 ViewControllerB 实例(通常,如果它在 VC 层次结构中比 A 更远),你不能得到通知调用。在 -initWithNibName:bundle: 中注册通知更有可能是您想要的。
  • 一个推论是:当您发送通知时,您的 ViewControllerB 实例必须存在才能被接收。如果您从 ViewControllerB 中的 MainStoryboard 加载 -nextView: ,则它尚未注册通知。
  • 关于ios - 使用 NSNotificationCenter 在 VC 之间发送数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15600079/

    10-10 20:37