延迟执行iOS应用程序

4

我正在寻找一种简单直接的方法,在iOS应用程序中延迟执行一定数量的帧,这可能吗?


不清楚你具体在问什么,但也许 NSTimer scheduledTimerWithTimeInterval 可以满足你的需求? - bengoesboom
小心术语,我认为你在谈论“延迟一定数量的”时可能来自另一个平台。你的意思是延迟一段时间间隔。 - Daniel
4个回答

10

根据你所做事情的复杂程度,这个小片段可能已经足够:

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //code to be executed on the main queue after delay
});
否则,您可以使用NSTimer来安排一些代码的执行。您甚至可以重复执行一次或多次。

例如,可以像这样使用:

[NSTimer scheduledTimerWithTimeInterval:5.0 
                                 target:self 
                               selector:@selector(myMethod) 
                               userInfo:nil 
                                repeats:NO];

对于更多关于如何使用NSTimer的详细信息,请查看此篇文章,当然还要查看文档


2

David 是正确的。这里是一些代码,展示我如何使用NSTimer。

-(void)startAnimating {
    [NSTimer scheduledTimerWithTimeInterval:.3 target:self selector:@selector(animateFirstSlide) userInfo:nil repeats:NO];
    self.pageTurner = [NSTimer scheduledTimerWithTimeInterval:6.0 target:self selector:@selector(turnPages) userInfo:nil repeats:YES];
}

-(void)animateFirstSlide {
    [self animateSlideAtIndex:0];
}

-(void)stopPageTurner {
    [self.pageTurner invalidate];
}

谢谢大家的回复,我现在有很多可以尝试的东西了。 - Balthatczar

2
如果您指的是一些常量时间,通常的做法是使用NSTimer在将来某个时间点触发,或者使用dispatch_after(),它可以在将来的某个时间点将块分派到主队列或后台队列。

1
你可以使用[NSTimer scheduledTimerWithTimeInterval: target: selector:]方法,或者也可以使用内置方法wait(time_in_seconds);
希望这可以帮到你。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接