簡單介紹下NSNotificationCenter

來源:互聯網
上載者:User

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方法調用後,之前添加的觀察者就會收到通知了,當然,前提是這兩個訊息名要相同。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.