siyuan926

一个NSNotificationCenter对象简单地说,通知中心提供了一个程序的广播信息机制一个NSNotificationCenter对象基本上是通知调度表

 

做个简单例子,利用广播机制在两个view之间传递消息,示例功能:TestOneController弹出TestTwoController,并传值给TestTwoController

=====================================================================================================

参数说明:

  addObserver 这个是观察者,就是说 在什么地方接收通知;

  selector    这个是收到通知后,调用何种方法;

  name:      这个是通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。

  发送通知,就是说此时要调用观察者处的方法。


  postNotificationName:通知的名字,也是通知的唯一标示,编译器就通过这个找到通知的。
  object:  新通知的对象(不是很理解,也能用来传参)
  userInfo:传递的参数

 

 

=====================================================================================================
//  TestOneController.m

View Code
-(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

View Code
- (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);
  
}

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-11-10
  • 2021-09-13
  • 2022-02-08
  • 2022-12-23
  • 2021-09-17
猜你喜欢
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2021-10-01
相关资源
相似解决方案