NoviceDeveloper
NoviceDeveloper

Reputation: 225

Unable to get NSTimer to work

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

Upvotes: 0

Views: 139

Answers (3)

Stark
Stark

Reputation: 441

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

Upvotes: 1

Ram Yadlapalli
Ram Yadlapalli

Reputation: 34

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]);}}

Upvotes: 0

Ignacio Inglese
Ignacio Inglese

Reputation: 2605

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

Upvotes: 1

Related Questions