iOS 通知的3种使用方式

方法一 不传递参数, 最常用的一种
// 发送通知
-(void)btn1Click
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"noti1" object:nil];
}
//监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti1) name:@"noti1" object:nil];

//调用方法
-(void)noti1{
NSLog(@"接收 不带参数的消息”);
}
方法二 使用object 传递消息
-(void)btn2Click:(UIButton *)btn
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"noti2" object:[NSString stringWithFormat:@"%@",btn.titleLabel.text]];
}
//监听
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti2:) name:@"noti2" object:nil];
//掉用方法
-(void)noti2:(NSNotification *)noti
{
//使用object处理消息
NSString *info = [noti object];
NSLog(@"接收 object传递的消息:%@",info);
}

方法三 使用userInfo 传递消息
1。通知页面

            NSDictionary *dict =@{@"userName":@"haha”};
            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeBgColor" object:nil userInfo:dict];

2.接受处理页面
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeBgColor:) name:@"changeBgColor" object:nil];

  • (void)changeBgColor:(NSNotification *)notification{
    [self.navigationController popViewControllerAnimated:YES];
    }
    3.移除通知

-(void)dealloc{
NSLog(@"移除了所有的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self];
//第二种方法.这里可以移除该控制器下名称为tongzhi的通知
//移除名称为tongzhi的那个通知
NSLog(@"移除了名称为tongzhi的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];

你可能感兴趣的:(iOS 通知的3种使用方式)