// 取到通知中心
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
//提供通知的名字,携带的对象、携带的信息,通知中心来创建通知并发送
[nc postNotificationName:@"showText" object:nil userInfo:@{@"showText":_textFiled.text}];
2.接收通知界面:
//添加监听 名字为:showText 的通知
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
//注册监听showText通知
//第一个参数:监听通知的对象
//第二个参数:接收到通知后要调用的方法
//第三个参数:监听通知的名字
[nc addObserver:self selector:@selector(showText:) name:@"showText" object:nil];
//接收到通知时调用的方法
-(void)showText:(NSNotification *)notify
{
UILabel *label = (id)[self.view viewWithTag:10];
//取出发送的文字
NSString *userInfo = [notify.userInfo objectForKey:@"showText"];
//显示文字
label.text = userInfo;
}
-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
总结:
先由第二个界面取到通知中心发送通知,然后在反向传值的接收数值的第一个界面创建一个监听者,注册监听对象 ,确定监听通知的名字和监听到通知之后的事件,最后再 移除观察者。
附:
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"changeColor" object:nil];
}
return self;
}
viewDidLoad之前执行
举例2.
通知的使用流程
首先,我们在需要接收通知的地方注册观察者,比如:
1
2
3
4
|
//获取通知中心单例对象
NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
//添加当前类对象为一个观察者,name和object设置为nil,表示接收一切通知
[center addObserver:self selector:@selector(notice:) name:@
"123"
object:nil];
|
之后,在我们需要时发送通知消息
1
2
3
4
|
//创建一个消息对象
NSNotification * notice = [NSNotification notificationWithName:@
"123"
object:nil userInfo:@{@
"1"
:@
"123"
}];
//发送消息
[[NSNotificationCenter defaultCenter]postNotification:notice];
|
我们可以在回调的函数中取到userInfo内容,如下:
1
2
3
|
-(
void
)notice:(id)sender{
NSLog(@
"%@"
,sender);
}
然后移除通知:
-(void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; }
|
打印结果如下: