广播机制分为:注册----发送------------接收(接收方),具体请看一下代码。
1,在要发送数据的视图页面.m文件处理发送逻辑的方法里注册+发送
- (IBAction)pressed:(ID)sender { // [self performSegueWithIDentifIEr:@"second" sender:self]; NSLog(@"send message:%@",firstFIEld.text); //页面跳转传值方法二:利用notification NSDictionary *dicts = [NSDictionary dictionaryWithObjectsAndKeys:@"one1",@"one",@"two2",@"two",@"three3",@"three",nil]; //注册(第一步) NSNotification *notification =[NSNotification notificationWithname:@"mynotification" object:firstFIEld.text]; //发送(第二步) [[NSNotificationCenter defaultCenter] postNotification:notification]; //注册+发送也可以一行完成(等效于以上两行) [[NSNotificationCenter defaultCenter] postNotificationname:@"mynotification2" object:dicts];//发送一个字典过去}
notificationWithname:参数的值是自己定义,接收方以此名称为接收标识。
2,在跳转后,接收数据视图页面.m文件中处理逻辑的方法里 接收
- (voID)vIEwDIDLoad{ [super vIEwDIDLoad]; // Do any additional setup after loading the vIEw. //接受端:接受(第一步) [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(notificationHandler:) name:@"mynotification" object:nil]; [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(notificationHandler2:) name:@"mynotification2" object:nil];}//自定义接收信息和处理的方法(第二步)-(voID) notificationHandler:(NSNotification *) notification{ secondFIEld.text = [notification object];//收到消息后在UItextFIEld中显示出来}//自定义接收字典信息的方法-(voID) notificationHandler2:(NSNotification *) notification2{ NSDictionary *dict = [notification2 object]; NSLog(@"receive dict :%@,forkey:%@",dict,[dict objectForKey:@"one"]);}
注意:如果注册的notification在目标视图没有收到或名称写错,目标视图的相关方法就不会执行
总结以上是内存溢出为你收集整理的广播机制传值 iOS NSNotification全部内容,希望文章能够帮你解决广播机制传值 iOS NSNotification所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)