IOS延时执行函数详解

来源:互联网 发布:台企怎么样知乎 编辑:程序博客网 时间:2024/05/17 05:11

目前所知ios延时函数有如下四种:

1、performSelector方法

[self performSelector:@selector(delayFun) withObject:nil afterDelay:1.0f];

此方法以非阻塞的方式执行,且必须在主线程中执行,否则无效。该方法暂时未找到取消执行的方法。


2、定时器:NSTimer

[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(delayFun) userInfo:nil repeats:NO];

此方法以非阻塞的方式执行,且必须在主线程中执行,否则无效。可以通过NSTimer类的- (void)invalidate;取消执行。


3、 sleep方式

[NSThread sleepForTimeInterval:1.0f]; 

[self delayFun];

此方法以阻塞的方式执行,建方放到子线程中,以免卡住界面,且在任意线程中均可执行。没有找到取消执行的方法。


4.GCD方式

double delayInSeconds = 5.0; 

__block ViewController* bself = self; 

dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));

dispatch_after(delayTime, dispatch_get_main_queue(), ^(void){ 

[bself delayFun]; });

此方法以非阻塞的方式执行,且在任意线程中均可执行。没有找到取消执行的方法。


0 0
原创粉丝点击