回呼(callback)就是把一段可執行的程式碼與某個特定事件綁在一起,事件發生時自動執行。Objective-C 提供了四條路徑,各有適用場合,選錯了程式碼就會變得難讀。
目標-動作對(Target-Action)
在開始等待事件前先說好:「事件發生時,向這個物件送出這個訊息。」接收訊息的物件是 target,訊息的 selector 就是 action。
輔助物件(Helper Object)
「事件發生時,向遵守某協議的輔助物件送訊息。」delegate 與 data source 都是常見的輔助物件。
通知(Notification)
透過通知中心:先告訴它「某物件正在等某些通知」,事件發生時由相關物件發通知給中心,中心再轉發給等待者。
Block
宣告一個 Block,事件發生時把它執行起來。
此外還有一個常被忽略的角色:NSRunLoop。RunLoop 實例持續待命,特定事件發生時就觸發回呼。上面四種機制其實都得跑在 RunLoop 之上。
int main(int argc, const char * argv[]) {
@autoreleasepool {
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
建立一個 BNRLogger 類別作為 NSTimer 的 target,每兩秒呼叫一次 updateLastTime:。
#import <Foundation/Foundation.h> @interface BNRLogger : NSObject<NSURLSessionDataDelegate> @property (nonatomic) NSDate *lastTime; - (NSString *)lastTimeString; - (void)updateLastTime:(NSTimer *)t; @end
#import "BNRLogger.h"
@implementation BNRLogger
- (NSString *)lastTimeString {
static NSDateFormatter *dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLog(@"created dateFormatter");
}
return [dateFormatter stringFromDate:self.lastTime];
}
- (void)updateLastTime:(NSTimer *)t {
NSDate *now = [NSDate date];
[self setLastTime:now];
NSLog(@"Just set time to %@", self.lastTimeString);
}
@end
#import <Foundation/Foundation.h>
#import "BNRLogger.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BNRLogger *logger = [[BNRLogger alloc] init];
__unused NSTimer *timer =
[NSTimer scheduledTimerWithTimeInterval:2.0
target:logger
selector:@selector(updateLastTime:)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
把 BNRLogger 設為 session 的 delegate,網路狀態變化時系統就會回頭呼叫它。
#import <Foundation/Foundation.h>
#import "BNRLogger.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BNRLogger *logger = [[BNRLogger alloc] init];
// URL 是一張圖片的下載鏈接
NSURL *url = [NSURL URLWithString:@"https://image.baidu.com/search/down?tn=download&word=download"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
__unused NSURLSession *session =
[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]
delegate:logger
delegateQueue:[NSOperationQueue mainQueue]];
__unused NSTimer *timer =
[NSTimer scheduledTimerWithTimeInterval:2.0
target:logger
selector:@selector(updateLastTime:)
userInfo:nil
repeats:YES];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request];
[dataTask resume];
[[NSRunLoop currentRunLoop] run];
}
return 0;
}
標頭檔宣告協議:
#import <Foundation/Foundation.h> @interface BNRLogger : NSObject<NSURLSessionDataDelegate> @property (nonatomic, strong) NSMutableData *responseData; @property (nonatomic) NSDate *lastTime; - (NSString *)lastTimeString; - (void)updateLastTime:(NSTimer *)t; @end
實作三個關鍵代理方法:
#import "BNRLogger.h"
@implementation BNRLogger
- (NSMutableData *)responseData {
if (_responseData == nil) {
_responseData = [NSMutableData data];
}
return _responseData;
}
- (NSString *)lastTimeString {
static NSDateFormatter *dateFormatter = nil;
if (!dateFormatter) {
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSLog(@"created dateFormatter");
}
return [dateFormatter stringFromDate:self.lastTime];
}
- (void)updateLastTime:(NSTimer *)t {
NSDate *now = [NSDate date];
[self setLastTime:now];
NSLog(@"Just set time to %@", self.lastTimeString);
}
// 1. 接收到伺服器回應時呼叫
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
NSLog(@"didReceiveResponse--%@", [NSThread currentThread]);
// 注意:必須用 completionHandler 回呼告訴系統如何處理資料,預設是取消
/* NSURLSessionResponseCancel = 0, 取消
NSURLSessionResponseAllow = 1, 接收
NSURLSessionResponseBecomeDownload = 2, 變成下載請求
NSURLSessionResponseBecomeStream 變成串流 */
completionHandler(NSURLSessionResponseAllow);
}
// 2. 收到資料時呼叫,資料大時會呼叫多次
- (void)URLSession:(NSURLSession *)session
dataTask:(NSURLSessionDataTask *)dataTask
didReceiveData:(NSData *)data {
NSLog(@"didReceiveData--%@", [NSThread currentThread]);
[self.responseData appendData:data];
}
// 3. 請求完成(成功或失敗)時呼叫
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
NSLog(@"didCompleteWithError--%@", [NSThread currentThread]);
if (error == nil) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:self.responseData
options:kNilOptions
error:nil];
NSLog(@"%@", dict);
}
}
@end
系統時區變動時會發出 NSSystemTimeZoneDidChangeNotification,通知中心再轉給觀察者。
// 加在「輔助物件」範例的 main.m 中
[[NSNotificationCenter defaultCenter] addObserver:logger
selector:@selector(zoneChange:)
name:NSSystemTimeZoneDidChangeNotification
object:nil];
// 加在 BNRLogger.m 中
- (void)zoneChange:(NSNotification *)note {
NSLog(@"The system time zone has changed!");
}
把上面那段 addObserver 換成帶 block 的版本:
[[NSNotificationCenter defaultCenter] addObserverForName:NSSystemTimeZoneDidChangeNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSLog(@"The system time zone has changed!");
}];
同時把 BNRLogger.m 裡的 zoneChange: 方法刪掉。好處是回呼邏輯就在註冊處,閱讀時不必在檔案之間跳來跳去;代價是 block 會強引用外層物件,忘了移除觀察者時容易釀成循環引用。