美文网首页
iOS: 延迟执行的几种方法

iOS: 延迟执行的几种方法

作者: cukiy | 来源:发表于2018-12-05 17:00 被阅读0次

一. performSelector

/**
 第一个参数:需要延迟执行的方法
 第二个参数:要传入的参数(id类型)
 第三个参数:延迟的时间
*/
[self performSelector:@selector(testMethod1:) withObject:@"aaa" afterDelay:5.0];

二. NSTimer

// 1.延迟执行某一段代码
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 repeats:NO block:^(NSTimer * _Nonnull timer) {
 // 需要延迟执行的代码
}];

// 2.延迟执行某一个方法
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(testMethod1:) userInfo:nil repeats:NO];

// 如果使用上面两种延迟执行的方法,建议将定时器添加到NSRunLoop的Common模式中,防止其他控件的交互影响到定时器
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

// 取消定时器
[timer invalidate];
// 取消的同时要销毁定时器
timer = nil;

三. NSThread

//该方法使当前线程进入休眠状态来达到延迟的目的
// 只有一个参数:延迟的时间
[NSThread sleepForTimeInterval:5.0];

四. GCD

// 第一个参数:延迟的时间
// 可以通过改变队列来改变线程
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
   // 需要延迟执行的代码
};

相关文章

网友评论

      本文标题:iOS: 延迟执行的几种方法

      本文链接:https://www.haomeiwen.com/subject/gtywcqtx.html