多个计时器Objective-C

时间:2014-03-11 08:50:44

标签: ios objective-c timer

我的iPhone应用程序有一些问题,它有三个计时器,其中两个基于主计时器初始化。 Timer1 Timer2 可以根据主计时器的时间来更改标签。现在,程序在我的热身阵列中移动非常快(不是每30秒就像它应该的那样)。

- (void)viewDidLoad
{    
     //these arrays hold strings 
    warmup = [[NSMutableArray alloc] initWithObjects:c1,c2,c3,c4,c5,c6, nil];

    legs = [[NSMutableArray alloc] initWithObjects:l,l2,l3,l4,l5,l6,l,l2,l3,l4,l5,l6,nil];

    //main timer for the program 
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

-(void)timerFired
{
    if((currMinute>0 || currSeconds>=0) && currMinute>=0)
    {
        UIProgressView *progressView = [[UIProgressView alloc] init];
        progressView.frame = CGRectMake(10,350,200,500);

        [self.view addSubview:progressView];

        if(currSeconds==0)
        {
            currMinute-=1;
            currSeconds=59;
        }
        else if(currSeconds>0)
        {
            currSeconds-=1;
        }
        if(currMinute>-1)
            [progress setText:[NSString stringWithFormat:@"%@%d%@%02d",@"Time : ",currMinute,@":",currSeconds]];

        [progressView setProgress:currMinute animated:YES];
    }
    else
    { 
        [timer invalidate];
    }

    if (currMinute>=27) 
    {
        title.text = @"warm-up";
        timer1 = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(rotatewarmup)userInfo:nil repeats:YES];
    }
    else if (currMinute<27) 
    {
        [timer1 invalidate];
        title.text = @"leg workout";
        timer2=[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(rotatelegs)userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer: timer2 forMode: NSDefaultRunLoopMode];
    }
}

-(void)rotatewarmup
{
    counter++ ;
    label45.text = [NSString stringWithFormat:@"workout: %@ ", [warmup objectAtIndex:counter]];
}

//the other function does the same but with the other array. 

1 个答案:

答案 0 :(得分:1)

你的问题在于,如果currMinute&gt; = 27,你每秒初始化一次timer1。每次初始化时,您的计数器都会递增。这就是为什么你的程序如此快速地运行在预热阵列中的原因。也许试试这个:

if (currMinute>=27) 
    {
        title.text = @"warm-up";
        if(!timer1)
            timer1 = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(rotatewarmup)userInfo:nil repeats:YES];
    }
else{
        [timer1 invalidate];
        title.text = @"leg workout";
        if(!timer2){            
            timer2=[NSTimer scheduledTimerWithTimeInterval:60.0 target:self selector:@selector(rotatelegs)userInfo:nil repeats:YES];
            [[NSRunLoop currentRunLoop] addTimer: timer2 forMode: NSDefaultRunLoopMode];
        }
    }

与timer2相同。这是如何工作的:代码首先检查计时器是否先前已经初始化,如果是,则不会重新初始化它。