我需要使用NSMutableDictionary
将ViewControllerA
从一个班级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];
}
答案 0 :(得分:2)
您对NSNotificationCenter
方法的调用很好。需要考虑的一些事项:
ViewControllerB
个实例在调用-viewWillAppear:
之前不会注册通知,因此如果您尚未显示ViewControllerB
的实例(通常情况下,如果它在VC层次结构中比A)更远,则无法获得通知调用。在-initWithNibName:bundle:
注册通知更有可能是您想要的。
其必然结果是:当您发送通知以便收到通知时,您的ViewControllerB
实例必须存在。如果您从ViewControllerB
MainStoryboard
加载-nextView:
,则表示尚未注册该通知。