使用2个NSTimers时出现问题

时间:2015-03-13 10:44:06

标签: ios objective-c nstimer

我正在开发一款iOS应用程序,可以通过应用程序提供/拨打电话。我们可以一个接一个地打两个电话。我们第一次打电话。一旦建立了呼叫,就应该触发NSTimer并显示呼叫的持续时间。

为此,我正在为计时器

做跟进
self.switchTimer1 = [NSTimer scheduledTimerWithTimeInterval:1.0
                                 target:self
                                 selector:@selector(setTimerLabel1:)
                                 userInfo:nil
                                 repeats:YES];

[self.switchTimer1 fire];
建立第一次通话后,用户可以进行第二次通话。

一旦建立第二个呼叫,它将触发第二个计时器。

if (hasSecondCall)
{

    self.switchTimer2 = [NSTimer scheduledTimerWithTimeInterval:1.0
                                     target:self
                                     selector:@selector(setTimerLabel2:)
                                     userInfo:nil
                                     repeats:YES];

    timeSec=0;

    timeMin=0;

    [self.switchTimer2 fire];

}

在第一次拨打两个电话时工作正常。

假如我结束了第二次通话并且再次拨打电话,那个时间第二个定时器在建立呼叫之前定时器自动呼叫并且一旦呼叫建立,定时器递增值就像双值显示一样快。比如,2,4,6等

对于后面的射击方法之后的第二时间

- (void)setTimerLabel2:(NSTimer *)timer {

    timeSec=timeSec+1;

    NSLog(@"timeSec+1 %d",timeSec+1);

    if (timeSec == 60)
    {
        timeSec = 0;
        timeMin=timeMin+1;
    }

    NSString* timeNow = [NSString stringWithFormat:@"%02d:%02d", timeMin, timeSec];

    [_switchCallLCD setStatus:timeNow labelNumber:2];
}

在断开呼叫时,我们按照

进行呼叫
- (void)endingCallWithId:(UInt32)call_id {

    if (hasSecondCall&& call_id==_current_call) {

        if (self.switchTimer2) {

            //NSLog(@"self.predictNumber %@",self.predictNumber);
            self.predictNumber=self.predictNumber2;
            [_lcd setText:self.predictNumber];

            [self.switchTimer2 invalidate];
            self.switchTimer2 = nil;
            [self.switchTimer2 release];
            [_switchCallLCD setStatus:NSLocalizedString(@"call ended",nil) labelNumber:2];

            timeSec = 0;
            timeMin = 0;
        }

我在这个问题上搜索了很多论坛,但我无法找到解决方案。我听说,如果我们使用多个计时器就会出现这样的问题。

1 个答案:

答案 0 :(得分:0)

您可能仍然运行了之前的计时器实例。当你进行第二组调用时,你会运行2个switchTimer1实例和2个switchTimer2实例。

一旦结束通话,您需要使计时器无效:

[self.switchTimer1 invalidate];

然后将其设置为nil以获得良好的衡量标准:

self.switchTimer1 = nil;