通知(Notification)是 iOS 中用來做「一對多」物件溝通的機制,跟 delegate 互補。本文把通知中心、通知物件、發布與接收、以及常見的注意事項一次講清楚。
通知中心本身就是單例,透過下面的寫法取得:
[NSNotificationCenter defaultCenter];
一個完整的通知通常有三個屬性:
- (NSString *)name; // 通知名稱 - (id)object; // 發布者 - (NSDictionary *)userInfo; // 附帶的額外資訊
建立通知物件的方式:
- (instancetype)initWithName:(NSString *)name object:(id)object userInfo:(NSDictionary *)userInfo; + (instancetype)notificationWithName:(NSString *)aName object:(id)anObject; + (instancetype)notificationWithName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
- (void)postNotification:(NSNotification *)notification; - (void)postNotificationName:(NSString *)aName object:(id)anObject; - (void)postNotificationName:(NSString *)aName object:(id)anObject userInfo:(NSDictionary *)aUserInfo;
這部分包含註冊與取消註冊兩件事。特別注意:通知中心不會 retain 觀察者,所以任何註冊過通知的物件,都必須在自己釋放之前取消註冊。否則通知再次送達時,通知中心仍會向已釋放的物件發訊息,結果就是崩潰。
註冊觀察者:
- (void)addObserver:(id)observer selector:(SEL)aSelector name:(NSString *)aName object:(id)anObject;
// observer:接收通知的物件
// aSelector:收到通知後被呼叫的方法,通知物件會當參數傳入
// aName:通知名稱;若為 nil 則不論名稱為何都會收到(等於收全部)
// anObject:通知發布者;若 aName 與 anObject 皆為 nil,則所有通知都會收到
- (id <NSObject>)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *note))block;
// queue:決定 block 在哪個佇列執行,傳 nil 則預設在當前佇列同步執行
取消註冊:
- (void)removeObserver:(id)observer;
- (void)removeObserver:(id)observer name:(NSString *)aName object:(id)anObject;
// 一般寫在觀察者即將銷毀時
- (void)dealloc {
// [super dealloc]; 非 ARC 環境才需要
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
UIDevice 通知:[UIDevice currentDevice] 提供電量、電池狀態、機型、系統版本等資訊,並持續發布以下通知:
UIDeviceOrientationDidChangeNotification // 裝置方向旋轉 UIDeviceBatteryStateDidChangeNotification // 電池狀態改變 UIDeviceBatteryLevelDidChangeNotification // 電量改變 UIDeviceProximityStateDidChangeNotification// 距離感測器(例如貼近臉部)
鍵盤通知:需要依鍵盤彈出/收起調整版面時,監聽這組通知即可。
UIKeyboardWillShowNotification // 即將顯示 UIKeyboardDidShowNotification // 顯示完成 UIKeyboardWillHideNotification // 即將隱藏 UIKeyboardDidHideNotification // 隱藏完成 UIKeyboardWillChangeFrameNotification // 位置尺寸即將改變 UIKeyboardDidChangeFrameNotification // 位置尺寸改變完成
鍵盤通知的 userInfo 常用 key:
UIKeyboardFrameBeginUserInfoKey // 動畫開始時的 frame UIKeyboardFrameEndUserInfoKey // 動畫結束後的最終 frame UIKeyboardAnimationDurationUserInfoKey // 動畫時間 UIKeyboardAnimationCurveUserInfoKey // 動畫節奏曲線
實作上通常拿 EndFrame 減掉螢幕高度,就能知道鍵盤佔掉多少空間,進而決定要往上推多少。