Richard
Richard

Reputation: 125

Pause NSTimer when leaving that view and continue counting when come back?

I'm new in xcode and objective-c and trying to developing an app. I would like to set up a timer in some of pages for calculating how much time user spend in that page. In the app, I have 5 theme pages, each pages contains a table view to another 3 sub-pages. I would like to add a counter to these 3 pages (5*3) but not including theme pages themselves. The page shift is controlled by navigation bar. I have put some codes as follows in .m file of viewcontroller.

- (void)viewDidLoad  
{
[super viewDidLoad];
//timer
timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self 
                                       selector:@selector(handleTimer) 
                                       userInfo:nil 
                                        repeats:YES];
}

-(void)handleTimer
{
MainInt += 1;
self.TimeLabel.text = [NSString stringWithFormat:@"%d",MainInt];
}

and some code in .h file (Brett is one of the 3 sub-pages.)

@interface Brett : UIviewController
{
NSTimer *timer;
int MainInt;
}

@ property (weak, nonatomic) IBOutlet UILable *TimLable;

Every time when I leave the page and go back again the counter is always count from 0. Anyone can help to solve this problem??

Upvotes: 0

Views: 210

Answers (3)

Toseef Khilji
Toseef Khilji

Reputation: 17409

Every time it Count start form 0, I guess because of you are creating Brett object every time when you push it to navigation.

Create Global Timer in appDelegate class and use it, in viewWillAppear start timer and in viewWillDisappear pause that timer.

Upvotes: 3

HRM
HRM

Reputation: 2127

What I understood from your question is to simply keep track of the amount of time a user spend in sub pages. If my understanding is correct, then you may try following.

Create and start timer as like now you are doing. On viewWillDisAppear method of your controller, just update the global variable or NSUserDefaults value like this:

//Get the previous time available in userdefaults
int counter = [[NSUserDefaults standardUserDefaults] integerForKey:@"ScreenACounter"];
//Update the key with existing counter value + current timer value.
[[NSUserDefaults standardUserDefaults] setInteger:counter + currentTimer.Value  forKey:@"HighScore"];

Hope this helps.

Upvotes: 1

Adithya
Adithya

Reputation: 4705

Alternative to the other answer, you can just make the MainInt a static variable

static int MainInt; 

Upvotes: 1

Related Questions