通知NSNotificationCenter

添加通知

//UIColor *color;
//NSNotificationCenter  通知中心 ,單例類
//單例類:在整個(gè)應(yīng)用程序中只有一個(gè)對象,調(diào)用單利方法是,不管創(chuàng)建多少次,都是同一個(gè)對象
//defaultCenter 時(shí)通知中心的單利方法
NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:color,@"color", nil];
//postNotificationName 發(fā)通知
//參數(shù)1.通知的名字2.由誰發(fā)送通知3.發(fā)通知是需要傳遞的參數(shù)
[notiCenter postNotificationName:@"changeColor" object:self userInfo:dic];

接收通知

//參數(shù)1.由誰去接收通知2.接收到通知后,需要執(zhí)行的方法,如果方法需要傳參,參數(shù)是NSNotification的對象3.接受通知的名字,要和發(fā)送通知時(shí)名字保持一致(調(diào)頻一致);如果寫nil,默認(rèn)接受所有的通知4.是否指定通知的發(fā)送者,指定接受某一個(gè)對象發(fā)送的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiceChangeColorNotification:) name:@"changeColor" object:nil];

//接收到通知執(zhí)行的方法
-(void)receiceChangeColorNotification:(NSNotification*)noti
{
//noti.name 通知的名字
//noti.object 通知的發(fā)送者
//noti.userInfo 發(fā)送通知傳遞的參數(shù)
NSLog(@"接受到了改變顏色的通知:%@__%@__%@",noti.name,noti.object,noti.userInfo);
NSDictionary *dic = noti.userInfo;
UIColor *color = [dic objectForKey:@"color"];
self.view.backgroundColor = color;
}

當(dāng)給一個(gè)已經(jīng)釋放的對象(如一個(gè)自定義類)發(fā)送通知時(shí) 系統(tǒng)會立即崩潰 解決辦法是 在自定義類的 dealloc 方法中移除通知

//移除通知
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"classOver" object:nil];

系統(tǒng)自帶的通知

//應(yīng)用程序進(jìn)入到后臺的通知
//UIApplicationDidEnterBackgroundNotification 程序進(jìn)圖后臺的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationGotoBackGround) name:UIApplicationDidEnterBackgroundNotification object:nil];
//接受到鍵盤frame改變的通知
//UIKeyboardWillChangeFrameNotification 鍵盤frame將要改變的通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardFrameChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容