
iOS 的通知機制在多執行緒環境下,執行緒行為相當不受控。這句話是什麼意思?
依官方文件的說法:無論你在哪個執行緒註冊 observer,只要通知是在哪個執行緒 post,它就會在哪個執行緒被接收。用程式碼來驗證:
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"current thread = %@", [NSThread currentThread]);
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:POST_NOTIFICATION object:nil];
}
- (void)viewDidAppear:(BOOL)animated {
[self postNotificationInBackground];
}
- (void)postNotificationInBackground {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:POST_NOTIFICATION object:nil userInfo:nil];
});
}
- (void)handleNotification:(NSNotification *)notification {
NSLog(@"current thread = %@", [NSThread currentThread]);
}輸出如下:
2016-07-02 11:20:56.683 Test[31784:3602420] current thread = <NSThread: 0x7f8548405250>{number = 1, name = main}
2016-07-02 11:20:56.684 Test[31784:3602420] viewWillAppear: ViewController
2016-07-02 11:20:56.689 Test[31784:3602469] current thread = <NSThread: 0x7f854845b790>{number = 2, name = (null)}也就是說,即使我在主執行緒註冊了 observer,但因為在子執行緒 post 了通知,handleNotification 就會在子執行緒被觸發。這帶來一個很實際的困擾:通知回呼的執行緒變得不確定,而我們大量的操作(尤其是 UI 操作)必須在主執行緒進行。
- (void)handleNotification:(NSNotification *)notification {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"current thread = %@", [NSThread currentThread]);
});
}缺陷很明顯:每個回呼函式都得這樣寫一次。對開發者而言負擔太大,顯然是下策。
思路與上一種類似,但實作優雅得多。這個方案在蘋果官方文件中有詳細介紹,核心做法是:用一個通知佇列(注意,不是 NSNotificationQueue 物件,而是一個陣列)記錄所有被拋到非預期執行緒的通知,再把它們重定向回預期執行緒。
具體流程是:我們仍像平常一樣註冊觀察者;收到通知時,先判斷 post 出來的執行緒是否為我們期望的執行緒,若不是,就把這個通知存進自訂佇列,並送出一個信號(signal)到期望的執行緒,告知它有通知待處理。指定執行緒收到信號後,把通知從佇列中取出並處理。
/* Threaded notification support. */
@property (nonatomic) NSMutableArray *notifications; // 通知佇列
@property (nonatomic) NSThread *notificationThread; // 預想的處理通知的執行緒
@property (nonatomic) NSLock *notificationLock; // 用於對通知佇列加鎖,避免執行緒衝突
@property (nonatomic) NSMachPort *notificationPort; // 用於向預想的處理執行緒送訊號的通信埠
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"current thread = %@", [NSThread currentThread]);
[self setUpThreadingSupport];
// 往當前執行緒的 run loop 加入埠來源
// 當 Mach 訊息到達而接收執行緒的 run loop 沒有運行時,內核會保存這條訊息,直到下一次進入 run loop
[[NSRunLoop currentRunLoop] addPort:self.notificationPort forMode:(__bridge NSString *)kCFRunLoopCommonModes];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(processNotification:) name:POST_NOTIFICATION object:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:POST_NOTIFICATION object:nil userInfo:nil];
});
}
- (void)setUpThreadingSupport {
if (self.notifications) {
return;
}
self.notifications = [[NSMutableArray alloc] init];
self.notificationLock = [[NSLock alloc] init];
self.notificationThread = [NSThread currentThread];
self.notificationPort = [[NSMachPort alloc] init];
[self.notificationPort setDelegate:self];
[[NSRunLoop currentRunLoop] addPort:self.notificationPort forMode:(__bridge NSString*)kCFRunLoopCommonModes];
}
- (void)handleMachMessage:(void *)msg {
[self.notificationLock lock];
while ([self.notifications count]) {
NSNotification *notification = [self.notifications objectAtIndex:0];
[self.notifications removeObjectAtIndex:0];
[self.notificationLock unlock];
[self processNotification:notification];
[self.notificationLock lock];
};
[self.notificationLock unlock];
}
- (void)processNotification:(NSNotification *)notification {
if ([NSThread currentThread] != _notificationThread) {
// Forward the notification to the correct thread.
[self.notificationLock lock];
[self.notifications addObject:notification];
[self.notificationLock unlock];
[self.notificationPort sendBeforeDate:[NSDate date] components:nil from:nil reserved:0];
} else {
// Process the notification here;
NSLog(@"current thread = %@", [NSThread currentThread]);
NSLog(@"process notification");
}
}
@end這個方案有兩個明顯缺陷,官方文件也點明了:
所有通知的處理都必須經過 processNotification 函式。
所有接聽物件都得各自提供對應的 NSMachPort 進行訊息轉發。
正因如此,官方並不建議直接這樣使用,而是鼓勵開發者繼承 NSNotificationCenter,或自行提供一個獨立的類別來做執行緒維護。
為順應語法演進,蘋果自 iOS 4 起提供了帶 Block 的通知 API:
- (id<NSObject>)addObserverForName:(NSString *)name
object:(id)obj
queue:(NSOperationQueue *)queue
usingBlock:(void (^)(NSNotification *note))block幾點說明:
觀察者就是呼叫時的當前物件。
queue 定義了 block 的執行執行緒;傳 nil 則表示 block 與發通知在同一個執行緒執行。
block 就是該通知的處理函式。
這個 API 已經能讓我們方便地控制通知的執行緒切換,但移除觀察者的方式要注意。
先回想原本 NSNotification 的移除方式:
- (void)removeObservers {
[[NSNotificationCenter defaultCenter] removeObserver:self name:POST_NOTIFICATION object:nil];
}需要指定 observer 與 name。但 Block 版本不能這樣寫,必須改成:
- (void)removeObservers {
if (_observer) {
[[NSNotificationCenter defaultCenter] removeObserver:_observer];
}
}其中 _observer 是 addObserverForName 系列 API 回傳的觀察者物件。這意味著你得為每一個觀察者保存一個成員變數,移除時再逐一刪除。若需要十個觀察者,就得記十個成員變數——想想就很麻煩,而且無法方便地按 observer 指定。理想做法是再封裝一層,把這些細節收攏起來。
GitHub 上有個試圖解決上述問題的實作,使用方式如下:
+ (void)observeName:(NSString *)name
owner:(id)owner
dispatchQueue:(dispatch_queue_t)dispatchQueue
block:(LRNotificationObserverBlock)block;它能方便地控制執行緒切換,還能在 owner 被釋放時自動移除觀察者。也就是說,我們不必再為了 remove 而額外重寫 dealloc——很多時候我們在 viewDidLoad 註冊觀察者,就得再重載 dealloc 呼叫 removeObserver,這個方案把這份工作省掉了。
但如果你想顯式呼叫 remove 就比較麻煩(例如 viewWillAppear 註冊、viewWillDisappear 移除),它類似官方的解法,仍需逐一保存觀察者物件。
為了解決上述問題,於是決定重新寫一個通知管理類別,目標有兩個:
能方便地控制執行緒切換
能方便地移除觀察者
使用方式:
- (void)addObserver:(nonnull id)observer
name:(nonnull NSString *)aName
dispatchQueue:(nullable dispatch_queue_t)disPatchQueue
block:(nonnull GYNotificatioObserverBlock)block;我們提供了與官方 API 幾乎一致的呼叫形式,支援傳入 dispatchQueue 來控制執行緒,以 Block 處理訊息回呼,並支援在 observer 釋放時自動執行 remove。同時也提供了與原生一致的顯式移除方法:
- (void)removerObserver:(nonnull id)observer
name:(nonnull NSString *)anName
object:(nullable id)anObject;
- (void)removerObserver:(nonnull id)observer;GYNotificationCenter 借鑑了官方的執行緒重定向與 LRNotificationObserver 的部分方案。在 addObserver 時,會產生一個與 observer 關聯的 GYNotificationOberverIdentifer 物件,記錄傳入的 block 與 name,並依該 name 向通知中心註冊觀察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:anName object:object];
收到通知時,在 handleNotification 中執行傳入的 block,回呼到外部:
- (void)handleNotification:(NSNotification *)notification {
if (self.dispatchQueue) {
dispatch_async(self.dispatchQueue, ^{
if (self.block) {
self.block(notification);
}
});
} else {
self.block(notification);
}
}這些 GYNotificationOberverIdentifer 物件會被放進 GYNotificationOberverIdentifersContainer 中統一管理:
- (void)addNotificationOberverIdentifer:(GYNotificationOberverIdentifer *)identifier {
NSAssert(identifier, @"identifier is nil");
if (identifier) {
NotificationPerformLocked(^{
[self modifyContainer:^(NSMutableDictionary *notificationOberverIdentifersDic) {
// 不重複 add observer
if (![notificationOberverIdentifersDic objectForKey:identifier.name]) {
[notificationOberverIdentifersDic setObject:identifier forKey:identifier.name];
}
}];
});
}
}這個 container 也與 observer 關聯。由於 identifier 與 observer 是關聯關係,當 observer 釋放時 identifier 也會跟著釋放,因此可以在 identifier 的 dealloc 中呼叫 remove,从而实现自動移除。同時因為 container 保留了所有 identifier,也就能夠方便地依 name 進行移除:
- (void)removeObserverWithName:(NSString *)name {
if (name) {
NotificationPerformLocked(^{
[self modifyContainer:^(NSMutableDictionary *notificationOberverIdentifersDic) {
if ([notificationOberverIdentifersDic objectForKey:name]) {
GYNotificationOberverIdentifer *identifier = (GYNotificationOberverIdentifer *)[notificationOberverIdentifersDic objectForKey:name];
[identifier stopObserver];
[notificationOberverIdentifersDic removeObjectForKey:name];
}
}];
});
}
}整體來說,這套封裝同時兼顧了「執行緒可控」與「生命週期自動管理」兩件事,正是原生 API 一直沒被補上的部分。