user387184
user387184

Reputation: 11053

updating screen every minute automatically on iPhone

I have a countdown TextField which I like to update every minute automatically in my iPhone app.

When the specific screen is visible it should count down - when switching to another screen the countdown obviously must not be updated.

When returning to the screen the countdown should continue again...

What would be the correct way of handling this?

Many thanks!

Upvotes: 0

Views: 865

Answers (1)

Justin Paulson
Justin Paulson

Reputation: 4388

I would use an NSTimer. Here is the documentation for NSTimer.

Here is a snippet of code on how to set up a timer and get it to call a method:

NSTimer *theTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(updateTime) userInfo:nil repeats:NO];

This timer will call the updateTime method every time it fires. I have set it to NOT repeat, and instead, I would create a new timer each time I call the updateTime method. That way if you leave the UIViewController behind it will not keep firing the NSTimer.

Here is a generic updateTime method:

-(void) updateTime
{
    //Update user interface

    NSTimer *theTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(updateTime) userInfo:nil repeats:NO];
}

The timeInterval is in seconds, so this timer will keep firing every 60 seconds. You may wish to cut it a little shorter, like 30 seconds, or even 1 second and check the system time to see when you need to update your countdown.

I hope that helps!

Upvotes: 2

Related Questions