NSNotificationCenter 的使用-iPhone成长之路

iPhone中NSNotificationCenter,的使用很简单。

我们下面就看一看,通知的使用流程


1.某个页面,发布了通知,告诉应用程序,通知的内容,及接到响应后,做出的操作。


 

// 注册通知-播放页面

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(PlayVideo:)

                                                 name:@"PlayVideo"

                                               object:nil];


addObserver:self页面发布了名称为name:@"PlayVideo"的通知,当收到响应后,将执行selector:@selector(PlayVideo:)方法。


我们在另一个页面(本页面也是可以的,不过似乎没有必要啊,毕竟同一个页面可以相互访问,没必要再通过“通知”了)中,符合了某种条件,于是,该页面发送一个“通知“来告知"发送通知的主人"。这样,通知的主人,将开始执行响应的操作(PlayVideo:)。


2.发送通知来告知通知的主人

 

// 发送通知

    NSNotification *notification= [NSNotification notificationWithName:@"PlayVideo" object:showViewController userInfo:dict];

    [[NSNotificationCenter defaultCenter] postNotification:notification];


3.发送通知,后,通知的主人,得到了响应,于是开始执行相关方法:

 

-(void) PlayVideo:(NSNotification *)notification {

    

    if(notification.object && [notification.object isKindOfClass:[ShowViewController class]]){

        


            ShowViewController *view=(ShowViewController *)[notification object];

            NSDictionary *userInfo= [notification userInfo];

            UINavigationController* navController = (UINavigationController*)self.tabBarController.selectedViewController;

            if (navController!=Nil && view!=Nil) {

                

                [navController pushViewController:view animated:TRUE];

            }

        

    }


}


还有,忘记一个重要的东西,现在来补充一下。


注册&取消通知


当我们注册通知后,当不在需要使用时,要记得取消该通知。


比如,我们在viewDidLoad方法中,注册通知


 

- (void)viewDidLoad

{

    

    // 注册通知

    [[NSNotificationCenter defaultCenter] addObserver:self

                                             selector:@selector(controllSearchBarType)

                                                 name:@"controllSearchBarType"

                                               object:nil];


}


viewDidUnload方法中,取消通知


 

- (void)viewDidUnload{

    

    // 取消通知

    [[NSNotificationCenter defaultCenter]removeObserver:self

                                                   name:@"controllSearchBarType"

                                                 object:nil];

    

   

}


通知传递的参数有2个:

1.[notification object]

2.[notification userInfo]


就是这样,简单把,这就是通知。


通知主要用在:

1.不同的类,页面中传递信息。

2.在一些特定事件中,进行通知,也许通知并不执行太多操作,仅仅是作为一个该执行操作的"型号”。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值