-1

可能重复:
更改计时器的时间间隔

所以我有一个计时器:

timer=[NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];

而且我希望计时器每十秒减少一次,scheduledTimerWithTimeInterval 在十秒后达到 1.5,然后在 10 秒后达到 1.0... 是否有可能做到这一点,如果可能的话,我该怎么做?

4

3 回答 3

2

创建计时器后,您将无法对其进行修改。要更改计时器间隔,请使旧计时器无效并使用新间隔创建一个新计时器。

于 2011-10-09T15:33:10.557 回答
0

您将需要一组或一系列计时器,每个不同的时间间隔都有一个。当您想更改为时间序列中的下一个时间间隔时,停止/使一个计时器无效并启动下一个计时器。

于 2011-10-09T17:39:34.053 回答
0

您不必使用多个计时器,您所要做的就是添加一个用于时间间隔的变量,然后创建一个使计时器无效的方法,更改变量并再次启动计时器。例如,您可以创建一个启动计时器的方法。

int iTimerInterval = 2;

-(void) mTimerStart {
    timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(createNewImage) userInfo:nil repeats:YES];
}

-(void) mTimerStop {
    [timer invalidate];

    iTimerInterval = iTimerInterval + 5;

    [self mTimerStart];
}

这将是减少定时器间隔并保持定时器运行的简单方法,但我个人更喜欢使用下面的方法,因为它确保定时器只运行一次,这样它就不会复制实例,迫使你应用程序变得故障,它也让你的事情变得更容易。

int iTimerInterval = 2;
int iTimerIncrementAmount = 5;
int iTimerCount;
int iTimerChange = 10; //Variable to change the timer after the amount of time
bool bTimerRunning = FALSE;

-(void) mTimerToggle:(BOOL)bTimerShouldRun {
    if (bTimerShouldRun == TRUE) {
        if (bTimerRunning == FALSE) {
            timer = [NSTimer scheduledTimerWithTimeInterval:iTimerInterval target:self selector:@selector(mCreateNewImage) userInfo:nil repeats:YES];
            bTimerRunning = TRUE;
        }
    } else if (bTimerShouldRun == FALSE) {
        if (bTimerRunning == TRUE) {
            [timer invalidate];
            bTimerRunning = FALSE;
        }
    }
}

-(void) mCreateNewImage {
    //Your Code Goes Here

    if (iTimerCount % iTimerChange == 0) { //10 Second Increments
        iTimerInterval = iTimerInterval + iTimerIncrementAmount; //Increments by Variable's amount

        [self mTimerToggle:FALSE]; //Stops Timer
        [self mTimerToggle:TRUE]; //Starts Timer
    }

    iTimerCount ++;
}

-(void) mYourMethodThatStartsTimer {
    [self mTimerToggle:TRUE];
}

我没有完成所有的编码,但这就是你需要的大部分。只需改变一些东西,你就会很高兴!

于 2011-10-10T02:52:32.507 回答