一. 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(), ^{
// 需要延迟执行的代码
};
网友评论