Ios 使用NSNotificationCenter在VCs之间发送数据

Ios 使用NSNotificationCenter在VCs之间发送数据,ios,objective-c,uiviewcontroller,nsnotificationcenter,nsnotification,Ios,Objective C,Uiviewcontroller,Nsnotificationcenter,Nsnotification,我需要使用NSNotificationCenter将NSMutableDictionary从一个类(ViewControllerA)传递到另一个类(ViewControllerB)。我已经尝试了以下代码,但它不起作用。我实际上传递给了ViewControllerB,但是没有调用-receiveData方法。有什么建议吗?谢谢 ViewControllerA.m - (IBAction)nextView:(id)sender { [[NSNotificationCenter default

我需要使用
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];
}
- (void)receiveData:(NSNotification *)notification {
    NSLog(@"Data received: %@", [notification userInfo]);
}

- (void)viewWillAppear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(receiveData:)
     name:@"PassData"
     object:nil];
}
ViewControllerB.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];
}
- (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
    实例将不会注册通知,直到
    -ViewControllerB出现:
    已被调用,因此如果您尚未显示
    ViewControllerB
    的实例(通常,如果它在VC层次结构中比A更靠下),则无法获得通知调用。在
    -initWithNibName:bundle:
    中注册通知更有可能是您想要的

  • 这样做的一个推论是:
    ViewControllerB
    的实例在发送通知时必须存在,以便接收通知。如果您正在从
    -nextView:
    中的
    MainStoryboard
    加载
    ViewControllerB
    ,则它尚未注册通知


  • 在这种情况下,为什么要使用通知?通常,当您需要广播一个事件(可能包含附加数据)时,会使用通知,而广播者不关心谁或有多少其他类对该事件感兴趣。在这种情况下,您似乎只需要确保ViewControllerA仅在VCA创建和显示VCB时将一些数据传递给ViewControllerB。为什么不让VCA在VCB上设置一个属性而不是使用通知?