NSNotification广播实现视图跳转传递数据
广播机制分为:注册->发送->接收(接收方)
第一步,在要发送数据的视图页面.m文件处理发送逻辑的方法里注册+发送
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| - (IBAction)pressed:(id)sender {
NSLog(@"send message:%@",firstField.text);
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:参数的值是自己定义,接收方以此名称为接收标识。
第二步,在跳转后,接收数据视图页面.m文件中处理逻辑的方法里 接收
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| - (void)viewDidLoad { [super viewDidLoad]; [[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];
}
-(void) notificationHandler2:(NSNotification *) notification2{
NSDictionary *dict = [notification2 object]; NSLog(@"receive dict :%@,forkey:%@",dict,[dict objectForKey:@"one"]);
}
|
注意:如果注册的notification在目标视图没有收到或名称写错,目标视图的相关方法就不会执行