ios開發中有時會用到NSNotificationCenter,其實NSNotificationCenter的原理是一個觀察者模式,包括了觀察者的註冊、通知及刪除等。
獲得NSNotificationCenter的方法只有一種,那就是[NSNotificationCenter defaultCenter],通過調用靜態方法defaultCenter就可以擷取這個通知中樞的對象了,而NSNotificationCenter是一個單例模式,而這個通知中樞的對象會一直存在於一個應用的生命週期。
很多訊息都會通過通知中樞分發,比如你想在鍵盤收合時做一些事情,就可以寫一個方法,比如叫keyboardDidHide:,然後只需要加上如下代碼:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
這樣,就可以在鍵盤收合的時候調用當前類的keyboardDidHide:方法了。類似UIKeyboardDidHideNotification這樣的訊息名還有很多,如UIKeyboardDidShowNotification,UIWindowDidResignKeyNotification等等。
我們如果想定製自己的訊息名也是很簡單的
NSNotificationCenter *notifyCenter = [NSNotificationCenter defaultCenter];
[notifyCenter addObserver:self selector:@selector(等到通知後調用的方法) name:你的訊息名,必須是NSString類型 object:nil];
而發送這個訊息其實也只需幾行代碼
NSNotificationCenter * notifyCenter = [NSNotificationCenter defaultCenter];
NSNotification *nnf = [NSNotification notificationWithName:你的訊息名,必須是NSString類型 object:建立一個NSNotification需要的的對象];
[notifyCenter postNotification:nnf];
當postNotification方法調用後,之前添加的觀察者就會收到通知了,當然,前提是這兩個訊息名要相同。