免费开源的iOS开发学习平台

UINavigationController介绍:14-使用通知逆传数据(目标VC->源VC)

导航控制器管理的子控制器之间进行数据逆向传递,除了使用代理之外,还可以使用通知(NSNotification)以及Block。本节介绍一下如何使用通知。

使用通知实现数据逆传的步骤

与代理相比,通知的优点在于可以支持一对多的进行数据传递。使用通知进行数据逆向传递,可以按照如下步骤进行编码。

  • 在源控制器SourceViewController.m中,注册观察者
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveMessage:) name:@"destinationVCReturn" object:nil];
}
  • 在源控制器SourceViewController.m中,实现收到通知后的操作,即实现receiveMessage:方法。从目标控制器中传递的通知中,携带了传递过来的数据对象。
-(void) receiveMessage:(NSNotification *) notification {
    NSString *string = (NSString *) notification.object;
    NSLog(@"目标控制器回传的字符串数据(使用通知):%@",string);
}
  • 不要忘记在源控制器SourceViewController.m中,在dealloc方法中移除观察者
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
  • 在目标控制器DestinationViewController.m中,在目标控制器出栈前(调用popViewControllerAnimated:方法前),推送通知给各个观察者,在推送的通知中传递需要交互的数据对象。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"destinationVCReturn" object:@"九九学院"];
    [self.navigationController popViewControllerAnimated:YES];
}
  • 运行结果如下图所示:

示例代码

https://github.com/99ios/9.2.14