1.发送
/*观察者使用:
1.注册某个对象成为观察者
1.1任何NSObject(或其子类)的对象,都可以通过通知中心注册成为某条广播的观察者
1.2一条广播的观察者可以有多个
2.被观察的对象发送广播 --> 观察者可以接收到特定的广播
*/
//点击按钮,通过通知中心发送广播
//1.只通知,不传参给下个页面
// [[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:nil];
//2.既通知,也通过userInfo传参给下个页面
//userInfo:存储要传递的内容
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"威廉" forKey:@"add"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"change" object:nil userInfo:dict];
2.接收
{
/*
第一个参数:观察者对象 --> self
第二个参数:选择器。选择器放的是接收到广播后要做的
第三个参数:广播的名字.发送处和接收处名字要保持一致
第四个参数:从发送广播的对象处得到的object --> nil
*/
//当观察者(self)接收到广播(change)后,会执行相应的方法(reloadUI:)
//如果注册成为观察者时,同时设置了name和object,那么当前观察者能接收到的广播,必须满足条件 --> name和object与观察者的name和object一致
//如果注册成为观察者时,未设置object,那么发送的广播是否设置object不影响观察者的接收。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUI:) name:@"change" object:nil];
}
//接收到广播后做出的相应处理
-(void)reloadUI:(NSNotification *)notifi{
NSLog(@"object = %@",notifi.object);
NSString *str = [notifi.userInfo objectForKey:@"add"];
//数据源中增加数据
[_dataArray addObject:str];
//刷新页面
[self.tableView reloadData];
3.销毁
//注销
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"change" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillBackFromClose) name:
UIApplicationWillResignActiveNotification object:nil];