您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

Objective-C 的四種回呼機制:Target-Action、輔助物件、通知與 Block

編輯:iOS 開發綜合

回呼(callback)就是把一段可執行的程式碼與某個特定事件綁在一起,事件發生時自動執行。Objective-C 提供了四條路徑,各有適用場合,選錯了程式碼就會變得難讀。

四種機制速覽

目標-動作對(Target-Action)
在開始等待事件前先說好:「事件發生時,向這個物件送出這個訊息。」接收訊息的物件是 target,訊息的 selector 就是 action。

輔助物件(Helper Object)
「事件發生時,向遵守某協議的輔助物件送訊息。」delegate 與 data source 都是常見的輔助物件。

通知(Notification)
透過通知中心:先告訴它「某物件正在等某些通知」,事件發生時由相關物件發通知給中心,中心再轉發給等待者。

Block
宣告一個 Block,事件發生時把它執行起來。

此外還有一個常被忽略的角色:NSRunLoop。RunLoop 實例持續待命,特定事件發生時就觸發回呼。上面四種機制其實都得跑在 RunLoop 之上。

先建立 RunLoop

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        [[NSRunLoop currentRunLoop] run];
    }
    return 0;
}

一、目標-動作對:NSTimer

建立一個 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;
}

二、輔助物件:NSURLSession 的 delegate

把 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!");
}

四、Block 回呼:把通知寫得更就地

把上面那段 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 會強引用外層物件,忘了移除觀察者時容易釀成循環引用。

怎麼選

  1. 只負責單一動作的物件,用目標-動作對。
  2. 功能較複雜的物件(如 NSURLSession),用輔助物件,最常見的就是 delegate。
  3. 需要觸發多個其他物件中回呼的物件(如 NSTimeZone),用通知。
  4. 想讓程式碼讀起來順一點,用 Block。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved