相較於 Android,iOS 的訊息處理機制更為多樣:既有近似監聽器的設計,也有近似廣播的方式。大致可以歸成三類:
若只是為了做 demo 而建立完整 iOS 專案,反而累贅,因此以下範例使用 macOS 的 Command Line Tool。
iOS/macOS 系統內部有一個持續運轉的 RunLoop。說它是「死循環」,是因為只要系統不關機,它就在背景不斷跑;說它是「活著的」,是因為它確實在完成有用的工作,處理我們看得見與看不見的事件。
#import <Foundation/Foundation.h>
@interface Logger : NSObject {
NSMutableData *incomingData;
}
- (void)sayhello:(NSTimer *)t;
- (void)zoneChange:(NSNotification *)note;
@end
#import "Logger.h"
@implementation Logger
// Target-action 的動作
- (void)sayhello:(NSTimer *)t {
NSLog(@"hello 你好!");
}
// Helper objects:NSURLConnection 的回呼
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"received %lu bytes", [data length]);
if (!incomingData) {
incomingData = [[NSMutableData alloc] init];
}
[incomingData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"got it all");
NSString *string = [[NSString alloc] initWithData:incomingData
encoding:NSUTF8StringEncoding];
incomingData = nil;
NSLog(@"string has %lu characters", [string length]);
NSLog(@"the all string: %@", string);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"connection fail %@", [error localizedDescription]);
incomingData = nil;
}
// Notification 的觀察方法
- (void)zoneChange:(NSNotification *)note {
NSLog(@"the system time zone has changed");
}
- (void)dealloc {
// 釋放該物件前必須移除通知觀察
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
在 main 中建立實例並啟動 RunLoop:
@autoreleasepool {
Logger *logger = [[Logger alloc] init];
// 在此掛上三種機制的程式碼
[[NSRunLoop currentRunLoop] run]; // 啟動那個無限循環
}
Notification:想要在系統時區變動時呼叫 Logger 的 zoneChange:,只需向通知中心註冊觀察者。
[[NSNotificationCenter defaultCenter] addObserver:logger
selector:@selector(zoneChange:)
name:NSSystemClockDidChangeNotification
object:nil];
它的效果是:Logger 會收到 zoneChange: 訊息。這是典型的「一對多」廣播模型,發送者不必知道誰在聽。
Helper objects:以 NSURLConnection 為例。
NSURL *url = [NSURL URLWithString:@"https://localhost"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
__unused NSURLConnection *conn = [[NSURLConnection alloc]
initWithRequest:request delegate:logger startImmediately:YES];
結果是 Logger.m 中所有帶 connection 前綴的方法被呼叫。這些方法在語意上就是一個協議,只是 Apple 當年沒有把它正式宣告為 protocol。
Target-action:以 NSTimer 為例。
__unused NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:logger
selector:@selector(sayhello:)
userInfo:nil
repeats:YES];
target 就是物件,action 就是方法。這行程式碼等於告訴 RunLoop:「每一秒幫我呼叫一次 sayhello:」。由於 RunLoop 不會停,輸出也就不會停。
把三者放在一起看,可以整理出一個簡單的分類依據:Notification 是一对多、發送者與接收者互不相識;Target-action 是一對一、由框架代為定時或觸發;Helper objects 則是「你把一個 delegate 交給某個物件,它在完成工作後依約定回呼你一組方法」。理解這三種模型的適用場合,比記住各自的 API 更重要。