OC中的几种延迟执行方式
生活随笔
收集整理的這篇文章主要介紹了
OC中的几种延迟执行方式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一種:
[UIView animateWithDuration:3 delay:3 options:1 animations:^{self.btn.transform = CGAffineTransformMakeTranslation(300, 400);} completion:^(BOOL finished) {NSLog(@"view animation結束");}]; //不會阻塞線程,animations block中的代碼對于是支持animation的代碼,才會有延時效果,對于不支持animation的代碼 則 不會有延時效果復制代碼第二種:
[NSThread sleepForTimeInterval:3]; //阻塞線程,浪費性能 ,一般不推薦用。此方式在主線程和子線程中均可執行。 建議放到子線程中,以免卡住界面,沒有找到取消執行的方法。 [self delayMethod]; 復制代碼第三種:最常用
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{}); //定制了延時執行的任務,不會阻塞線程,在主線程和子線程中都可以,效率較高(推薦使用)。此方式在可以在參數中選擇執行的線程。 是一種非阻塞的執行方式, 沒有找到取消執行的方法。 復制代碼第四種:
[self performSelector:@selector(test) withObject:nil afterDelay:3]; //此方式要求必須在主線程中執行,否則無效。 是一種非阻塞的執行方式. [[self class] cancelPreviousPerformRequestsWithTarget:self]; //取消本類中執行的performSelector:方法 復制代碼第五種:定時器
1)NSTimer
[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO]; //此方式要求必須在主線程中執行,否則無效。 是一種非阻塞的執行方式, 可以通過NSTimer類的- (void)invalidate;取消執行。 復制代碼2)dispatch_source_t(比 NSTimer 更準的定時器),也可以在子線程中執行,非阻塞執行方式
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);//開始時間 dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, 3.0 * NSEC_PER_SEC);//間隔時間 uint64_t interval = 2.0 * NSEC_PER_SEC;dispatch_source_set_timer(self.timer, start, interval, 0);//設置回調 dispatch_source_set_event_handler(self.timer, ^{[self delayMethod];dispatch_suspend(self.timer); });//啟動timer dispatch_resume(self.timer); 復制代碼發現個不錯的iOS進階視頻,感興趣可看一看:觀看地址
轉載于:https://juejin.im/post/5d0256fe518825738151f799
總結
以上是生活随笔為你收集整理的OC中的几种延迟执行方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 儿童过敏性鼻炎(小儿过敏性鼻炎怎么治才能
- 下一篇: 349元小米中枢网关可以省了,自己做个小