0

Using NSTimer for my application in which I have to show countdown timer with initial timing equal to 100sec. It shows 99,then 98..96..94..92...86 and so on. But I want each sec to show up. Here is my code....

   -(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];
    }
}
1
  • 1
    write timer method out side of your selector method Nov 30, 2011 at 6:00

3 Answers 3

1

Try following code

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--;
}
1

You are actually re-creating the timer every time your method gets called.

You should try leaving that outside and retaining it until you're finished with it.

@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
0

you have call updateTimerLabel outside the method. ex: -(void)viewDidLoad{timeRemaining=100.0;[self updateTimerLabel];countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];}

-(void)updateTimerLabel {if (timeRemaining>0 ) {timeRemaining=timeRemaining-1.0;NSLog(@"%@",[NSString stringWithFormat:@"%.0f",timeRemaining]);}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.