1、animateWithDuration(block中只对animation的代码有效)

/**
 * 不会阻塞线程,block中只支持animation代码,才会有延时效果,
 * 对于不支持animation的代码 则 不会有延时效果
 */
[UIView animateWithDuration:3 delay:3 options:1 animations:^{
        self.btn.transform = CGAffineTransformMakeTranslation(300, 400);
    } completion:^(BOOL finished) {
        NSLog(@"view animation结束");
 }];

2、sleepForTimeInterval(阻塞线程,浪费性能)

/**
 * 阻塞线程,浪费性能 ,一般不推荐用,甚至能不用就不用。
 * 此方式在主线程和子线程中均可执行。 
 * 建议放到子线程中,以免卡住界面,没有找到取消执行的方法。
 */
[NSThread sleepForTimeInterval:3];
[self delayMethod];

3、dispatch_after(推荐使用)

/**
* 定制了延时执行的任务,不会阻塞线程,在主线程和子线程中都可以,效率较高(推荐使用)。
* 此方式在可以在参数中选择执行的线程。 
* 是一种非阻塞的执行方式, 没有找到取消执行的方法。
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
 });

4、performSelector(主线程有效)

/**
* 此方式要求必须在主线程中执行,否则无效。
* 是一种非阻塞的执行方式, 暂时未找到取消执行的方法。
*/
[self performSelector:@selector(test) withObject:nil afterDelay:3];

5、定时器方式

5.1、NSTimer(主线程有效)


/**
* 此方式要求必须在主线程中执行,否则无效。
* 是一种非阻塞的执行方式, 可以通过NSTimer类的- (void)invalidate;取消执行。
*/
[NSTimer scheduledTimerWithTimeInterval:3.0f target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];

5.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);


版权声明:本文为weixin_38633659原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_38633659/article/details/113876789