OC—设计模式-通知的使用

通知

通知(广播)

可以一对多的发送通知(一个发送者 多个观察者)

特别注意:在发送者 发送通知的时候,必须有观察者

发送者,就是注册一个通知中心,以他为中心,发送消息

通过通知的名字,来判断是哪个通知

例子:老师通知男学生和女学生来开班会。

分析:老师是一个发送中心,则学生需要注意老师的发送的消息,他们为观察者

 

在老师的类里

 //建一个通知中心

-(void)speak{

    [[NSNotificationCenter defaultCenter]postNotificationName:@"老师的通知" object:nil userInfo:@{@“content":@"全班同学注意了,今天要开班会"}];

    }

在男学生的里

需要定义两个方法:一个方法是接收到老师的消息,第二个方法是对老师的消息做出判断

 

-(void)study{

    [ [ NSNotificationCenter defaultCenter]addObserver:self selector:@selector(jianCha) name:@"老师的通知" object:nil];  

}  

//在自己的类里使用,就不用声明了

-(void)jianCha{

    NSLog(@“我们要叫检查了。。”);

}

 

//最后移除观察者

-(void)dealloc{

    [ [ NSNotificationCenter defaultCenter] removeObserver : self];

}

在女学生的类里

//接收消息

-(void)note{

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(banHui : )  name:@"老师的通知" object:nil];

    

}

 

//NSNotification 包含了通知里面的所有内容

 

//这里有一个传值

-(void)banHui:(NSNotification *)message{

    NSLog(@"听老师说%@",message.userInfo[@"content"]);

}

 

//移除观察者

-(void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}

 最后在主文件里实现 

OC—设计模式-通知的使用