使用notification广播实现视图跳转传递数据

本文介绍如何使用iOS的通知中心实现ViewController间的通信,包括发送和接收自定义通知的过程,并演示了通过NSNotification传递简单数据和字典数据的方式。
第一个viewController:

  1. - (IBAction)pressed:(id)sender {  
  2.       
  3. //    [self performSegueWithIdentifier:@"second" sender:self];  
  4.     NSLog(@"send message:%@",firstField.text);  
  5.   
  6.       
  7.       
  8.     //页面跳转传值方法二:利用notification  
  9.     NSDictionary *dicts = [NSDictionary dictionaryWithObjectsAndKeys:@"one1",@"one",@"two2",@"two",@"three3",@"three", nil];  
  10.     //注册(第一步)  
  11.     NSNotification *notification  =[NSNotification notificationWithName:@"mynotification" object:firstField.text];  
  12.     //发送(第二步)  
  13.     [[NSNotificationCenter defaultCenter] postNotification:notification];  
  14.       
  15.     //注册+发送也可以一行完成(等效于以上两行)  
  16.     [[NSNotificationCenter defaultCenter] postNotificationName:@"mynotification2" object:dicts];//发送一个字典过去  
  17.   
  18.   
  19. }  



第二个viewController:


  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];  
  4.     // Do any additional setup after loading the view.  
  5.       
  6.     //接受端:接受(第一步)  
  7.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler:) name:@"mynotification" object:nil];  
  8.       
  9.       
  10.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationHandler2:) name:@"mynotification2" object:nil];  
  11.   
  12. }  
  13.   
  14. //自定义接收信息和处理的方法(第二步)  
  15. -(void) notificationHandler:(NSNotification *) notification{  
  16.       
  17.     secondField.text = [notification object];//收到消息后在UItextField中显示出来  
  18.   
  19. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值