Xcode Objective-C | iOS:延迟功能/ NSTimer帮助?

时间:2011-05-13 23:31:29

标签: objective-c xcode ios4 timer delay

所以我正在开发我的第一个iOS应用程序,我需要帮助..

现在的简单程序,我有大约9个按钮,当我按下第一个按钮或任何按钮时,我只想要第一个按钮突出显示60毫秒,不亮,第二个按钮高亮,等待60毫秒,不亮等等其余的按钮因此看起来像一个移动的LED。

我看起来已经尝试过睡眠/睡眠,但是一旦睡眠持续时间结束,它似乎就会一起跳过高亮/不高亮。

例如:

- (void) button_circleBusy:(id)sender{
firstButton.enabled = NO;
sleep(1);
firstButton.enabled = YES;

等等其他按钮。它会延迟,但它不会延迟“firstButton.enabled = NO;”。我为每个按钮的“禁用状态”画了一张照片,我从来没有看到它。

任何帮助表示赞赏!我已经研究过NSTimer,但我不确定如何实现它。

感谢。

-Paul

7 个答案:

答案 0 :(得分:50)

sleep不起作用,因为只有在主线程返回系统后才能更新显示。 NSTimer是要走的路。为此,您需要实现定时器调用以更改按钮的方法。一个例子:

- (void)button_circleBusy:(id)sender {
    firstButton.enabled = NO;
    // 60 milliseconds is .06 seconds
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
    firstButton.enabled = YES;
    secondButton.enabled = NO;
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...

答案 1 :(得分:47)

int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
     do something to the button(s)
});

答案 2 :(得分:29)

更少的代码是更好的代码。

[NSThread sleepForTimeInterval:0.06];

<强>夫特:

Thread.sleep(forTimeInterval: 0.06)

答案 3 :(得分:25)

稍微简洁的方法是使用performSelector:withObject:afterDelay: 它为您设置NSTimer对象,可以轻松取消

继续前面的例子,这将是

[self performSelector:@selector(goToSecondButton) withObject:nil afterDelay:.06];

更多info in the doc

答案 4 :(得分:16)

尝试

NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 0.06 ];
[NSThread sleepUntilDate:future];

答案 5 :(得分:3)

我想补充一下Avner Barr的答案。当使用int64时,似乎当我们超过1.0值时,函数似乎延迟不同。所以我想在这一点上,我们应该使用NSTimeInterval。

所以,最终的代码是:

NSTimeInterval delayInSeconds = 0.05;

dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

//do your tasks here

});

答案 6 :(得分:0)

[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];

是最好用的。使用睡眠(15);将导致用户无法执行任何其他操作。使用以下函数,您可以将goToSecondButton替换为适当的选择器或命令,也可以来自框架。