IOS中延時執行的幾種方式的比較

  1.  performSelector方法spa

    執行方法:線程

    [self performSelector:<#(SEL)#> withObject:<#(id)#> afterDelay:<#(NSTimeInterval)#>];
3d

    取消執行方法:code

    [ NSObject cancelPreviousPerformRequestsWithTarget:<#(id)#> selector:<#(SEL)#> object:<#(id)#> ];//這裏的方法是 NSObject的靜態方法orm

    特色:此方式要求必須在主線程中執行,不然無效。是一種非阻塞的執行方式。get

2.  NSTimerit

      執行方法:io

   NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(id)#> selector:<#(SEL)#> userInfo:<#(id)#> repeats:<#(BOOL)#>];form

   取消方法:thread

    [timer invalidate];//這裏的是減方法

   特色:此方式要求必須在主線程中執行,不然無效。是一種非阻塞的執行方式。

3. NSThread

    執行方法: 

    NSThread *thread = [[NSThread alloc]initWithTarget:<#(id)#> selector:<#(SEL)#> object:<#(id)#>];

   [NSThread sleepForTimeInterval:<#(NSTimeInterval)#>];

   [thread start];

   特色:此方式在主線程和子線程中都可執行。是一種阻塞的執行方式,建議放到子線程中。

4. dispatch_after 

double delayInSeconds = 2.0;

    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

    [dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

       // <#code to be executed on the main queue after delay#>

    }) ];//敲擊dispatch_after  代碼會自動生成

相關文章
相關標籤/搜索