通知類本身比較簡單,大概就分為注冊通知監聽器、發送通知,注銷通知監聽器三個方法;通知中心(NSNotificationCenter)采用單例的模式,整個系統只有一個通知中心,通過如下代碼獲取:
//獲取通知中心 [NSNotificationCenter defaultCenter];
注冊通知監聽器方法:
//observer為監聽器 //aSelector為接到收通知后的處理函數 //aName為監聽的通知的名稱 //object為接收通知的對象,需要與postNotification的object匹配,否則接收不到通知 - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;
發送通知的方法:
//需要手動構造一個NSNotification對象 - (void)postNotification:(NSNotification *)notification; //aName為注冊的通知名稱 //anObject為接受通知的對象,通知不傳參時可使用該方法 - (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject; //aUserInfo為將要傳遞的參數,類型為字典類型 //通知需要傳參數時使用下面這個方法,其他同上。 - (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
注銷通知監聽器方法:
//刪除通知的監聽器 - (void)removeObserver:(id)observer; //刪除通知的監聽器,aName監聽的通知的名稱,anObject監聽的通知的發送對象 - (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject; //以block的方式注冊通知監聽器 - (id <NSObject>)addObserverForName:(nullable NSNotificationName)name object:(nullable id)obj queue:(nullable NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *note))block API_AVAILABLE(macos(10.6), ios(4.0), watchos(2.0), tvos(9.0));
使用情況:
NSNotificationCenter類一般用于一個對象傳遞事件給另外一個對象,在另一個對象中觸發某些方法,可以實現跨視圖的交互。我在最近一個月內用到了兩次NSNotificationCenter類。
①在對項目進行國際化時,在切換語言時采用通知的方式,使其他界面進行刷新(需要在主線程內)。
②使用SGPagingView時,需要實現pageContentView中的內容在多選狀態時,pageTitleView禁止進行切換的功能??戳薙GPagingView提供的方法是沒有這個的,所以就采用了NSNotificationCenter。在進入多選狀態時發一條通知,在退出多選狀態時發一條通知(方法比較簡陋,如果有更好的方法請不吝賜教)。
//注冊通知監聽器 [NotifyUtil addNotify:NOTIFY_DISABLE_SWITCH Observer:self selector:@selector(disableSwitch) Object:nil]; [NotifyUtil addNotify:NOTIFY_ALLOW_SWITCH Observer:self selector:@selector(allowSwitch) Object:nil]; //調用方法 //禁止pageTitleView進行切換 -(void)disableSwitch{ self.pageTitleView.userInteractionEnabled = NO; } //允許pageTitleView進行切換 -(void)allowSwitch{ self.pageTitleView.userInteractionEnabled = YES; } //注銷通知監聽器 - (void) dealloc{ [NotifyUtil removeNotify:NOTIFY_DISABLE_SWITCH Observer:self]; [NotifyUtil removeNotify:NOTIFY_ALLOW_SWITCH Observer:self]; }
注:用NotifyUtil對NSNotificationCenter類進行了一個簡單的封裝,參數基本都一致,就不貼NotifyUtil的代碼了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。