延迟执行的常用方法

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值