使用NSNotificationCenter 事件通知

來源:互聯網
上載者:User
                                                 使用NSNotificationCenter 事件通知
         在進行與伺服器通訊的時候,經常是一個UI類去請求伺服器資料,然後伺服器將回調到appDelegate,這個時候我以前的做法是在AppDelegate中儲存 和維護這個UI類的指標,然後appDelegate在收到返回訊息的時候,如果這個UI類的指標還存在,並且不為NULL,那麼就直接調用UI類的指標。這種方法太麻煩了。

         今天才發現有NSNotificationCenter這個東東。                  使用方法如下:      (1)首先註冊 要接收Notification的對象  到 NSNotificationCenter,一般這段代碼放在init或者onEnter裡面。
        代碼如下:
        NSString* const strFuckMe = @"FuckMe";   

   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onFuckme:)
  name:strFuckMe object:nil];

   第一個參數是要接收Notification的對象,第二個參數是響應函數,第三個是通知的名稱,第四個參數表示接收哪個寄件者的通知,如果第四個參數為nil,接收所有寄件者的通知。

  (2)既然init裡面註冊了這個通知,那麼就需要在dealloc裡面移除這個通知的註冊:

      代碼如下:

   

      [[NSNotificationCenter  defaultCenter] removeObserver:self
 name:strFuckMe object:nil];
 



  (3)怎麼發送Notification通知呢?

   代碼如下:

   

   如果不需要傳遞參數的通知:

   

    [[NSNotificationCenter
defaultCenter] postNotificationName:strFuckMe
object:nil];


   如果要傳遞參數的通知:

   SFuckRet sFuckRet;

   NSValue* value = [NSValuevalueWithBytes:&sFuckRetobjCType:@encode(SFuckRet)];

   [[NSNotificationCenter defaultCenter] postNotificationName:strFuckMe object:nil userInfo:[NSDictionarydictionaryWithObjectsAndKeys:value,@"value",nil]];


  SFuckRet是一個定長的結構體對象,所以需要用NSValue來封裝以下,才能放到Object-c的容器中。

  postNotificationName參數是要發送的通知的名字,object:參數是一個id,一般可以傳遞self,可以讓接收通知者能調用的發送通知者。

  userInfo是一個NSDictionary可以傳遞自己的其他資訊。一般資料都放在這個裡面。


  注意一般NSValue一般用來封裝定長的結構體,CGRect,CGPoint什麼的,千萬不能包含指標之類的東西。


  (4)如何處理通知呢?

   代碼如下:

   

   

- (void)onFuckme NSNotification*)notification

{

   
NSDictionary* user_info = [notification userInfo]; 

   
NSValue* value = [user_info objectForKey:@"value"];

   
SFuckRet sfuckRet;

    [value
getValue:&sfuckRet];

}

NSDictionary* user_info = [notification userInfo]; 這句代碼就是取出PostNitifycation的時候設定的NSDictionary資訊。


這樣就取出來了所要傳遞的結構體啦。



   

     

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.