day11- 模擬通知

購(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)毀前,移除通知。
  • 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];
      

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。