1

基本上,我有一系列按钮,我想一个接一个地迭代和突出显示(除其他外),中间有一个延迟。似乎是一项简单的任务,但我似乎无法让它在保持响应的同时干净地工作。

我从这个开始:

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似乎很麻烦。

4

2 回答 2

2

NSTimer 将非常适合这项任务。

计时器的动作将每 x 秒触发一次,其中 x 是您指定的。

重点是这不会阻塞它运行的线程。正如彼得在此答案的评论中所说,我说计时器在单独的线程上等待是不正确的。有关详细信息,请参阅评论中的链接。

于 2010-02-09T20:03:21.323 回答
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];
}
于 2010-02-09T20:12:55.233 回答