基本上,我有一个按钮阵列,我想要一个接一个地迭代和突出显示(以及其他内容),中间有一个延迟。这似乎是一项简单的任务,但我似乎无法在保持响应的同时干净利落地工作。
我从这开始:
for MyButton *button in buttons {
[button highlight];
[button doStuff];
usleep(800000); // Wait 800 milliseconds.
}
但它没有反应,所以我尝试使用运行循环。
void delayWithRunLoop(NSTimeInterval interval)
{
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:interval];
[[NSRunLoop currentRunLoop] runUntilDate:date];
}
for MyButton *button in buttons {
[button highlight];
[button doStuff];
delayWithRunLoop(0.8); // Wait 800 milliseconds.
}
然而,它也没有反应。
有没有合理的方法呢?使用线程或NSTimer
s。
答案 0 :(得分:2)
NSTimer将非常适合这项任务。
计时器的动作将持续x秒,其中x是您指定的。
重点是这不会阻止它运行的线程。正如彼得在对这个答案的评论中所说的那样,我说定时器等待一个单独的线程是错误的。有关详细信息,请参阅注释中的链接。
答案 1 :(得分:1)
没关系,Jasarien是对的,NSTimer
非常适合。
- (void)tapButtons:(NSArray *)buttons
{
const NSTimeInterval waitInterval = 0.5; // Wait 500 milliseconds between each button.
NSTimeInterval nextInterval = waitInterval;
for (MyButton *button in buttons) {
[NSTimer scheduledTimerWithTimeInterval:nextInterval
target:self
selector:@selector(tapButtonForTimer:)
userInfo:button
repeats:NO];
nextInterval += waitInterval;
}
}
- (void)tapButtonForTimer:(NSTimer *)timer
{
MyButton *button = [timer userInfo];
[button highlight];
[button doStuff];
}