iOS 四种延迟执行的方法

来源:互联网 发布:java 监听模式原理 编辑:程序博客网 时间:2024/04/30 04:40

师弟疑问之延迟某个方法的执行怎么弄

1、实现延迟执行的方法有四种
performSelector系列的performSelector:withObject:afterDelay:
NSTimer的scheduledTimerWithTimeInterval:target:selector:useInfo:repeats:
NSThread的sleepForTimeInterval:方法
GCD的despatch_after方法

2、四种方法的具体使用
公用延迟执行方法

- (void)delayMethod{    NSLog(@"delayMethod");}

Method1:performSelector

[self performSelector:@selector(delayMethod) withObject:nil/*可传任意类型参数*/ afterDelay:2.0];

注:此方法是一种非阻塞的执行方式,未找到取消执行的方法。

Method2:NSTimer定时器

NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(delayMethod) userInfo:nil repeats:NO];

注:此方法是一种非阻塞的执行方式,
取消执行方法:- (void)invalidate;即可

Method3:NSThread线程的sleep

[NSThread sleepForTimeInterval:2.0];

注:此方法是一种阻塞执行方式,建议放在子线程中执行,否则会卡住界面。但有时还是需要阻塞执行,如进入欢迎界面需要沉睡3秒才进入主界面时。没有找到取消执行方式。

Method4:GCD

__block ViewController/*主控制器*/ *weakSelf = self;dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0/*延迟执行时间*/ * NSEC_PER_SEC));dispatch_after(delayTime, dispatch_get_main_queue(), ^{    [weakSelf delayMethod];});`

注:此方法可以在参数中选择执行的线程,是一种非阻塞执行方式。没有找到取消执行方式。

3、你所说的阻塞与非阻塞的意思是什么意思?
意思是执行了延迟函数这句代码例如NSThread的sleepForTimeInterval后是不是立马执行,这句代码后面的语句。
例子:

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:10.0];    NSLog(@"gargawgawef");    [NSThread sleepForTimeInterval:8.0];    NSLog(@"NSThred");

输出结果:

 gargawgawef NSThred在这之后停顿了8秒 delayMethod

从输出结果就可以看出,performSelector:这句执行完后,没有立即执行延迟方法,而是立即执行下面的语句,也就是NSThread的sleep方法,然后在输出delayMethod

1 0
原创粉丝点击