購(gòu)物車(chē)01-搭建基本骨架
購(gòu)物車(chē)02-圓角按鈕處理
購(gòu)物車(chē)03-顯示數(shù)據(jù)
購(gòu)物車(chē)04-加號(hào)減號(hào)點(diǎn)擊處理
NSNotification - 通知
NSNotificationCenter - 通知中心
怎么發(fā)布通知?
-
注意順序
-
先在通知中心,注冊(cè)監(jiān)聽(tīng)器,
然后在創(chuàng)建通知, 接著 '通知中心',發(fā)布通知,
最后在監(jiān)聽(tīng)者銷(xiāo)毀前,移除通知。
-
先在通知中心,注冊(cè)監(jiān)聽(tīng)器,
-
NSNotificationCenter
需要做哪些 ?- 在'通知中心'注冊(cè)監(jiān)聽(tīng)器.
- 在'通知中心'發(fā)布通知.
-
dealloc
在'監(jiān)聽(tīng)者對(duì)象'銷(xiāo)毀前,移除監(jiān)聽(tīng)。- (void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
-
NSNotification
需要做哪些?- 創(chuàng)建'通知'
- 可以不創(chuàng)建,因?yàn)樵?code>NSNotificationCenter里面有方法創(chuàng)建。
-
示例代碼
-
監(jiān)聽(tīng)者:p1, 通知發(fā)布者:compAL.
當(dāng)'compAL'發(fā)布了'通知',就調(diào)用監(jiān)聽(tīng)者P1的getMessage: 方法。//注冊(cè)監(jiān)聽(tīng)器 [[NSNotificationCenter defaultCenter] addObserver:p1 selector:@selector(getMessage:) name:nil object:compAL]; //創(chuàng)建 "通知",且將通知發(fā)送到 "通知中心" [[NSNotificationCenter defaultCenter] postNotificationName:alNoteTest object:compAL]; [[NSNotificationCenter defaultCenter] postNotificationName:alNoteTemp object:compAL userInfo:@{@"title":@"medical is a problem"}];
- 匿名通知(沒(méi)有通知發(fā)布者的通知),
監(jiān)聽(tīng)者:p2, 通知發(fā)布者:nil.
不管發(fā)布者是誰(shuí),只要通知名稱(chēng)是'jdNoteTest',就調(diào)用監(jiān)聽(tīng)者的'getNews:'方法*[[NSNotificationCenter defaultCenter]addObserver:p2 selector:@selector(getNews:) name:jdNoteTest object:nil]; [[NSNotificationCenter defaultCenter] postNotificationName:jdNoteTest object:compJD]; [[NSNotificationCenter defaultCenter] postNotificationName:jdNoteTest object:compAL];
-
監(jiān)聽(tīng)者: p2, 通知名稱(chēng): nil
監(jiān)聽(tīng),通知發(fā)布者為'compAL'所發(fā)布的所有通知[[NSNotificationCenter defaultCenter] addObserver:p2 selector:@selector(getNews:) name:nil object:compAL]; [[NSNotificationCenter defaultCenter] postNotificationName:alNoteTest object:compAL];//?? [[NSNotificationCenter defaultCenter] postNotificationName:jdNoteTemp object:compAL];//?? [[NSNotificationCenter defaultCenter] postNotificationName:alNoteTemp object:compJD];//?
-
監(jiān)聽(tīng)者: p2, 通知名稱(chēng): nil, 通知發(fā)布者: nil
監(jiān)聽(tīng)所有通知[[NSNotificationCenter defaultCenter] addObserver:p2 selector:@selector(getNews:) name:nil object:nil]; [[NSNotificationCenter defaultCenter]postNotificationName:jdNoteName object:compJD]; [[NSNotificationCenter defaultCenter]postNotificationName:alNoteName object:compAL];
-
監(jiān)聽(tīng)者:p1, 通知發(fā)布者:compAL.