IOS中延时执行的几种方式的比较

走远了吗. 提交于 2019-12-03 08:44:09
  1.  performSelector方法

    执行方法:

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

    取消执行方法:

    [ NSObject cancelPreviousPerformRequestsWithTarget:<#(id)#> selector:<#(SEL)#> object:<#(id)#> ];//这里的方法是 NSObject的静态方法

    特点:此方式要求必须在主线程中执行,否则无效。是一种非阻塞的执行方式。

2.  NSTimer

      执行方法:

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

   取消方法:

    [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  代码会自动生成

  

   




标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!