gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 05:56:09 26 4
gpt4 key购买 nike

我需要使用 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 方法的调用没有问题。需要考虑的几件事:

  1. ViewControllerB 实例在 -viewWillAppear: 被调用之前不会注册通知,所以如果您没有显示 ViewControllerB (通常情况下,如果它在 VC 层次结构中比 A 更靠下),您无法收到通知调用。在 -initWithNibName:bundle: 中注册通知更有可能是您想要的。

  2. 一个推论是:当您发送通知时,您的 ViewControllerB 实例必须存在,这样通知才能被接收。如果您正在 -nextView: 中从 MainStoryboard 加载 ViewControllerB,那么它还没有注册通知。

    <

关于ios - 使用 NSNotificationCenter 在 VC 之间发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com