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

iOS 開發(63):GCD 的延遲執行三種寫法

編輯:iOS 開發綜合

前言

「三秒後幫我做這件事」是很常見的需求。iOS 提供三條路徑:NSObject 的 performSelector:withObject:afterDelay:、GCD 的 dispatch_after,以及 GCD 的 C 函式版本 dispatch_after_f。三者語意相同,適用場景略有差別。

寫法一:performSelector afterDelay

- (void) printString:(NSString *)paramString{
    NSLog(@"%@", paramString);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    /*
        延遲三秒執行 printString:
        withObject 為傳入參數
     */
    [self performSelector:@selector(printString:)
               withObject:@"Grand Central Dispatch"
               afterDelay:3.0];

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

三秒後控制台輸出:

2013-05-10 17:04:52.710 GCDAfterTest[2385:c07] Grand Central Dispatch

這個方法會在目前的 run loop 上排程,因此預設在主執行緒執行,適合更新 UI。若要取消,可搭配 cancelPreviousPerformRequestsWithTarget:selector:object:。

寫法二:dispatch_after 搭配 Block

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // 設定延遲秒數
    double delayInSeconds = 2.0;

    // 以 dispatch_time 建立相對目前時間的排程時刻
    dispatch_time_t delayInNanoSeconds =
        dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

    dispatch_queue_t concurrentQueue =
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_after(delayInNanoSeconds, concurrentQueue, ^(void){
        NSLog(@"Grand Center Dispatch!");
    });

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

兩秒後輸出:

2013-05-10 17:06:27.023 GCDAfterTest2[2435:1303] Grand Center Dispatch!

注意 NSEC_PER_SEC 的換算:dispatch_time 的第二個參數是 奈秒,不是毫秒也不是秒。若要在主執行緒執行,把佇列換成 dispatch_get_main_queue() 即可。

寫法三:dispatch_after_f 搭配 C 函式

void processSomething(void *paramContext){
    NSLog(@"Processing...");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    double delayInSeconds = 2.0;
    dispatch_time_t delayInNanoSeconds =
        dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);

    dispatch_queue_t concurrentQueue =
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    // 第三個參數為上下文指標,會原封不動傳給 C 函式
    dispatch_after_f(delayInNanoSeconds, concurrentQueue,
                     NULL,
                     processSomething);

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    self.viewController = [[[ZYViewController alloc] initWithNibName:@"ZYViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

兩秒後輸出:

2013-05-10 17:07:27.660 GCDAfterTest3[2476:1303] Processing...

怎麼選

  • 只是延遲呼叫一個物件方法、且要更新 UI:performSelector:afterDelay: 最簡短。
  • 延遲執行一段 Block、需要指定佇列與優先權:dispatch_after。
  • 已有 C 函式、想避免 Block 捕獲帶來的開銷:dispatch_after_f。

最後提醒一個常見誤解:dispatch_after 不是計時器,它只會延遲一次,不會重複觸發。若要週期性執行, GCD 的做法是 dispatch_source 計時器,傳統做法則是 NSTimer 或 CADisplayLink。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved