第一种:
[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://links.jianshu.com/go?to=https%3A%2F%2Fke.qq.com%2Fcourse%2F370213%3Ftuin%3D27e5325b>

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信