使用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資訊。
這樣就取出來了所要傳遞的結構體啦。