使用按钮执行一段代码几秒钟/分钟?

时间:2012-08-20 03:55:19

标签: ios xcode uibutton nstimer

我只想在用户按下开始按钮时运行某个方法20秒,并通过它自己停止而不是使用按钮来执行它。但是,如果用户在下一回合20秒后按下开始按钮,它也应该触发。 我如何使用NStimer来实现这个? 很抱歉没有发布任何代码 提前谢谢!

1 个答案:

答案 0 :(得分:3)

// Assume ARC - otherwise do the proper retains/releases
{
    NSTimer *timer; // keep a reference around so you can cancel the timer if you need to
    NSDate *timerDate;
}

- (IBAction)buttonPressed:(id)sender
{
    // disable button til the time has passed
    [sender setEnabled:NO];

    // make sure its diabled til we're done here
    timerDate = [NSDate date];
    NSTimeInterval interval = 1; // 1 gets you a callback every second. If you just wnat to wait 20 seconds change it
    // schedule it
    timer = [NSTimer ]scheduledTimerWithTimeInterval:time target:self selector:@selector(myTimeRoutine:) userInfo:nil repeats:YES];
}

- (void)myTimeRoutine:(NSTimer *)timer
{
    // do something ...

    NSTimeInterval interval = -[timerDate timeIntervalSinceNow]; // return value will be negative, so change sign
    if(interval >= 20) {
        // I'm done now
        myButton.enabled = YES; // so it can be tapped again
        [timer cancel];         // dont want to get any more messages
        timer = nil;            // ARC way to release it
        timerDate = nil;
    }
}