一个NSNotificationCenter对象(或简单地说,通知中心)提供了一个程序内的广播信息的机制。一个NSNotificationCenter对象基本上是通知调度表。
做个简单例子,利用广播机制在两个view之间传递消息,示例功能:TestOneController弹出TestTwoController,并传值给TestTwoController
=====================================================================================================
参数说明:
addObserver 这个是观察者,就是说 在什么地方接收通知;
selector 这个是收到通知后,调用何种方法;
name: 这个是通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
发送通知,就是说此时要调用观察者处的方法。
postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
object: 新通知的对象(不是很理解,也能用来传参)
userInfo:传递的参数
=====================================================================================================
// TestOneController.m
-(IBAction)buttonPressed:(id)sender { //先执行弹出TestTwoController,以便初始化时先注册一个通知 if (self.testTwoController==nil) { //初始化一个捆绑指定nib文件的视图控制器 testTwoController=[[TestTwoController alloc] initWithNibName:@"TestTwoController" bundle:nil]; } //使用默认动画效果,弹出TestTwoController [self presentModalViewController: self.testTwoController animated:YES]; //向之前注册的通知发送消息 NSDictionary *dictionary = [[NSDictionary alloc]initWithObjectsAndKeys:@'count',@'1',nil]; NSNotification* notification = [NSNotification notificationWithName:@"test" object:nil userInfo:dictionary]; [[NSNotificationCenter defaultCenter] postNotification:notification1]; }
=====================================================================================================
// TestTwoController.m
- (void)viewDidLoad { //注册一个通知,指定接收通知的对象(addObserver:self) [[NSNotificationCenter defaultCenter] addObserver:self selector: @selector(testmethod:) name:@"test" object: nil]; } //接受到通知后的执行方法 - (void)testmethod(NSNotification*)notification { NSDictionary * dic = [notification userInfo]; NSString *string = [dic objectForKey:@"1"]; NSLog(@"string:%@",string); }