iOS 項目中的NSNotification簡單使用

來源:互聯網
上載者:User

標籤:

iOS中NSNotification的簡單使用

好久沒有寫過部落格了,總是遇到問題查一下,今天查的又是一個老問題,想了想,還是記錄一下!今天在項目開發中遇到一個配置及時性處理的問題,想了想之後決定用通知實現,但是實現的時候發現對通知早就忘光了,去網上查了一下,覺得這是一個查過幾遍的問題了,覺得有必要自己也記錄一下,也算是寫一下讓自己記得也更加清晰一些!本文只是記錄了一下NSNotification的簡單使用方法(由於文筆不佳,以後定要常記錄一些遇到的問題,數遍能講出其中的緣由,此過程慢慢努力!)。

1.NSNotification 是響應式編程

發送方常用方法:

// 1.建立通知並發送

NSNotification *notification = [[NSNotification alloc] initWithName:@"refresh" object:self userInfo:nil] ;

[[NSNotificationCenter defaultCenter] postNotification:notification];

 

    // 2.直接發送一個通知名字(不需要額外訊息)

[[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:self];

 

    // 3.發送通知,並單獨建立UserInfo

NSDictionary *userInfo = @{@"name":@"xiaoyou"};

[[NSNotificationCenter defaultCenter] postNotificationName:@"refresh" object:self userInfo:userInfo];

接收方常用方法:

1、 設定監聽/*** 添加監聽*/-(void)addObserverToNotification{[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateLoginInfo:) name:@"refresh" object:nil];}

2.監聽執行的方法/*** 更新登入資訊,注意在這裡可以獲得通知對象並且讀取附加資訊*/-(void)updateLoginInfo:(NSNotification *)notification{

NSDictionary *userInfo=notification.userInfo;

 

NSObject *object = notification.object;

 

//重新整理資料

[self loadData];

}

3、 移除監聽-(void)dealloc{//移除監聽[[NSNotificationCenter defaultCenter] removeObserver:self];}

2.注意事項

接收方在析構方法中必須移除監聽,這個是編碼規範。

 

iOS 項目中的NSNotification簡單使用

聯繫我們

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