主要在一些界面之間跨度大的界面使用比如要從C界面?zhèn)鞯紸界面這樣或者多個地方需要執(zhí)行一個操作的時候燕耿。通知最好是在viewDidLoad這個方法中創(chuàng)建
首先在需要傳送得界面C界面創(chuàng)建通知
//創(chuàng)建通知
NSDictionary * dic = @{@"zhuce":@YES};
[[NSNotificationCenter defaultCenter] postNotificationName:@"approveSelf" object:nil userInfo:dic];
這只能傳一個字典男应,userInfo的返回就是一個字典
這是第二步啦亮隙,在接受通知的地方也創(chuàng)建通知接受的方法
接受通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(approveSelf:) name:@"approveSelf" object:nil];//傳值通知創(chuàng)建好啦
//實現(xiàn)通知的方法
-(void)approveSelf:(NSNotification *)notification{
BOOL approveBool = notification.userInfo[@"zhuce"];
if ( approveBool == YES) {
[self verificationType:Verification_idCardLight];
}
}
最后一步不要忘記哦砸紊,移除通知
//最好在dealloc這個方法中移除通知
-(void)dealloc{
//第一種方法.這里可以移除該控制器下的所有通知
// 移除當(dāng)前所有通知
NSLog(@"移除了所有的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self];
//第二種方法.這里可以移除該控制器下名稱為zhuce的通知
//移除名稱為zhuce的那個通知
NSLog(@"移除了名稱為zhuce的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"zhuce" object:nil];
}
這里注意:如果dealloc方法不調(diào)用苛谷,說明當(dāng)前有變量沒有被釋放盗忱,這時如果找不到問題所在治筒,也可以重寫控制器的返回按鈕backBarButtonItem事件屉栓,在返回的時候進(jìn)行移除通知操作
//返回上一層界面事件
-(void)backPreviousViewControllerAction{
//第一種方法.這里可以移除該控制器下的所有通知
// 移除當(dāng)前所有通知
NSLog(@"移除了所有的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self];
//第二種方法.這里可以移除該控制器下名稱為tongzhi的通知
//移除名稱為tongzhi的那個通知
NSLog(@"移除了名稱為tongzhi的通知");
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"tongzhi" object:nil];
// 返回上一層界面
[self.navigationController popViewControllerAnimated:YES];
}
配個圖