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

来源:互联网 发布:移动互联网数据报告 编辑:程序博客网 时间:2024/04/30 08:35
第一个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. }  

0 0
原创粉丝点击