標籤:
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簡單使用