设为首页 加入收藏

TOP

关于OC中的几种延迟执行方式
2019-08-26 06:59:11 】 浏览:30
Tags:关于 延迟 执行 方式

第一种:

[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);

 

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Mac-Navicat Premium For Mac 12 .. 下一篇Flutter 实现原理及在马蜂窝的跨..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目