NSNotificationCenter 通知中心实现传值

来源:互联网 发布:淘宝上买圣衣神话 编辑:程序博客网 时间:2024/06/11 14:20

         在使用通知中心进行传值,接收界面必须先监听。这是在编写程序时容易被忽略的,而且不容易发现错误。现在通过一段代码进行详细解释。

      有两个界面,第一个界面有一个UIButton控件,点击UIButton,将第值传给第二个界面:

AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]];

    _firstController = [[FirstViewControlleralloc]init];

    _secondController = [[SecondViewControlleralloc]init];

//在启动应用程序时,为了节省内存,第二个页面并没有加载,此时,第二个页面并没有做监听,所以第二个页面接受不到数据。所以我们可以给其加个颜色让程序启动时,第二个页面做监听

   _secondController.view.backgroundColor = [UIColor redColor];//修改代码

或者做如下改动:

 //@selector 可以跨类寻找方法,但在第二界面的.h文件中要进行定义

 [[NSNotificationCenter defaultCenter]addObserver:__secondController selector:@selector(notifiListen:)name:@"Msg" object:nil];

    self.window.rootViewController = _firstController;

    self.window.backgroundColor = [UIColor whiteColor];

    [self.windowmakeKeyAndVisible];

    returnYES;

}


FirsrtViewController.m中:

- (void)viewDidLoad

{

    [superviewDidLoad];

    UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeSystem];

    btn.frame =CGRectMake(100,100, 100, 30);

    btn.backgroundColor = [UIColorgrayColor];

    [btn setTitle:@"NSNOtifition"forState:UIControlStateNormal];

    [btn addTarget:selfaction:@selector(btnClick:)   forControlEvents:UIControlEventTouchUpInside];

    [self.viewaddSubview:btn];


}

//给UIButton添加点击事件

-(void)btnClick:(UIButton*)bt

{    NSArray *array =@[@"a",@"b"];

    //通过通知中心想外发送一包数据  第一个随便给参数,第二个传得参数

    [[NSNotificationCenterdefaultCenter]postNotificationName:@"Msg"object:array];

}


SecondViewController.h中

-(void)notifitionListen:(NSNotification*)notifi;

SecondViewController.m中

- (void)viewDidLoad

{

    [superviewDidLoad];

   // [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(notifiListen:)name:@"Msg"object:nil];   

}

-(void)notifiListen:(NSNotification*)n{

    //解析传递的数据

   NSLog(@"%@",[nobject]);

}


第一次写博客,有错误的地方希望各位大牛多多指正





0 0