四個簡單易用的demo,關於iOS定時器和延時的,非常好用。

來源:互聯網
上載者:User

標籤:ext   after   delay   nsdate   efault   控制   patch   好用   sch   

 

1,延時執行(不可重複)

 

[objc] view plain copy/**  ** delay 不可重複  **/  - (void)timerMethodA  {      [self performSelector:@selector(methodAEvent)                 withObject:nil                 afterDelay:2.0f];//延時時間  }    - (void)methodAEvent  {      NSLog(@"-- method_A");  }  

 

 


效果我直接截取控制台的日誌了,就不做UI了。

 

2,用NSTimer執行定時和延時(可重複)

 

[objc] view plain copy/**  ** timer 可重複  **/  - (void)timerMethodB  {      _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f  //間隔時間                                                target:self                                              selector:@selector(methodBEvnet)                                              userInfo:nil                                               repeats:YES];  }    - (void)methodBEvnet  {      count++;      NSLog(@"-- Method_B count: %d", count);            if (count >= 5) {          [_timer invalidate];    //重複5次,timer停止          NSLog(@"-- end");      }  } 

 

 

 

 

3,用dispatch_source_set_timer執行定時(可重複)

 

[objc] view plain copy/**  ** dispatch_time 可重複  **/  - (void)timerMethodC  {      __block int i = 0;      CGFloat duration = 1.0f;   //間隔時間      dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);      dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);            dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, duration * NSEC_PER_SEC, 0);      dispatch_source_set_event_handler(timer, ^{                    i++;          if (i > 5) {              dispatch_source_cancel(timer);  //執行5次後停止              NSLog(@"-- end");          }else{              NSLog(@"-- Method_C i:%d", i);          }      });      dispatch_resume(timer);  }  

 

 

 

 

4,用dispatch_after執行延時(不可重複)

 

[objc] view plain copy/**  ** dispatch_time 不可重複  **/  - (void)timerMethodD  {      CGFloat delayTime = 2.0f;   //延時時間      dispatch_time_t timer = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime *NSEC_PER_SEC));      dispatch_after(timer, dispatch_get_main_queue(), ^{          NSLog(@"-- Method_D time:%@", [NSDate date]);      });                                              }  

 

 

 

 

文章最後奉上demo

http://download.csdn.net/detail/xiongbaoxr/9417374

四個簡單易用的demo,關於iOS定時器和延時的,非常好用。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.