Skip to content

iOS — 延迟执行 #7

Open
Open

Description

@cssoul

相信前端同学对setTimeout一点都不陌生,我们常常用setTimeout来实现在指定的时间之后调用一个函数或执行一个代码片段。

比如:

var timeoutID;

//延迟执行弹窗
function delayedAlert() {
  timeoutID = window.setTimeout(slowAlert, 2000);
}

//清除定时器
function clearAlert() {
  window.clearTimeout(timeoutID);
}

function slowAlert() {
  alert("这是一个弹窗!");
}

利用延迟执行,可以让我们的网页交互变的更加丰富,甚至可以做一些比较有意思的动画效果。通常使用了setTimeout后,我们要用clearTimeout来清除定时器,从而释放内存;

那么在iOS开发中,我们同样也会用到延迟执行的场景,并且还有好几种方法来实现延迟执行。

我们先定义一个公用方法,方便延迟调用

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

接下来再来介绍这些我们常用的延迟执行方法。

1、performSelector

[self performSelector:@selector(delayMethod) withObject:nil afterDelay:0.1];

有时候我们常常遇到一个bug,利用上面这种方式,延迟执行delayMethod方法就可以解决。

但是我们并不能100%确保所需要的数据或环境能在0.1s内准备完成,所以通常还是会有可能隐藏一些不可预见的问题,建议大家不要用这种方式来解决bug。

那如何替代这个方案呢,如果delayMethod需要的数据和环境是在主线程执行的,那么方案很简单:

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self delayMethod]; 
});

2、NSTimer定时器

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

注:此方法是一种非阻塞的执行方式,

//取消执行定时器
- (void)invalidate;

3、NSThread线程的sleep

[NSThread sleepForTimeInterval:2.0];

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

4、GCD

__block ViewController(控制器) weakSelf = self;

dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
dispatch_after(delayTime, dispatch_get_main_queue(), ^{
    [weakSelf delayMethod];
});

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

Activity

  1. changed the title [-]IOS — 延迟执行[/-] [+]iOS — 延迟执行[/+] on May 5, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions