无法让NSTimer工作

时间:2011-11-30 05:57:08

标签: iphone nstimer

在我的应用程序中使用NSTimer,我必须显示倒数计时器,初始时间等于100秒。它显示99,然后98..96..94..92 ... 86等等。但我希望每一秒出现。这是我的代码......

   -(void)updateTimerLabel{
   if (timeRemaining>0 ) {



    timeRemaining=timeRemaining-1.0;
    timerLabel.text=[NSString stringWithFormat:@"%.0f", timeRemaining];


    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];
    }
}

3 个答案:

答案 0 :(得分:1)

每次调用方法时,您实际上都在重新创建计时器。

你应该尝试将它留在外面并保留它直到你完成它。

@interface SomeClass

NSTimer * aTimer;

@end

@implementation

- (void)createTimer {
    aTimer = [[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES] retain];
}

- (void)updateTimerLabel {
    // do timer updates here

    // call [aTimer release]
    // and [aTimer invalidate]
    // aTimer = nil;
    // when you're done
}

@end

答案 1 :(得分:1)

尝试以下代码

int i =100;

-(void)viewDidLoad
{
[super viewDidLoad];
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(theActionMethod) userInfo:nil repeats:YES];  

}

-(void)theActionMethod
{
   if(i > 0)
   {
      NSString *str = [NSString stringWithFormat:@"%d",i];
      lbl.text = str;
   }
   i--;
}

答案 2 :(得分:0)

您已在方法外调用updateTimerLabel。 例如: - (void)viewDidLoad {timeRemaining = 100.0; [self updateTimerLabel]; countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel)userInfo:nil repeats:YES];}

- (无效)updateTimerLabel {if(timeRemaining> 0) {timeRemaining = timeRemaining-1.0; NSLog(@“%@”,[NSString stringWithFormat:@“%。0f”,timeRemaining]);}}