tags:

views:

206

answers:

3

I'd like a static time indicator that counts from 0 to whatever as time passes. The game I'm making will change after a certain number of days has passed. I'm sure this is a simple question, but how I can I store the total time passed, even between launches?

So..., first launch, time = 0;
Second launch an hour later time = 60;
Third launch, a day later, time = 86460;

and so on, just assume no time was spent in the app for this example, but of course, I'd like it to keep incrementing while they app is open as well. I'd imagine I have to store a value somewhere, then compare it to the (current time - last time) and add the numbers together, but I'm not sure how to do this. Thanks.

A: 

I do something similar in one of my apps. What I do is store the date and time when the app is first launched. The, each subsequent time the app is launched, do a subtraction of the first launch timestamp from the current time timestamp. While my app is open, I continually increment.

Edit:

I save the time stamp to NSUserDefaults by doing this:

NSString *timestamp = [NSString stringWithFormat:@"%d", (long)[[NSDate date] timeIntervalSince1970]];  
[[NSUserDefaults standardUserDefaults] setObject:timestamp forKey:@"timestamp"];
Justin Gallagher
How do you store the time stamp between launches?
nullArray
See above for edits
Justin Gallagher
+2  A: 

Use NSUserDefaults to store the amount of time in seconds that has passed from the first launch in a key and the date and time of the last launch of your app in another key. When you start your app, read the values and add to the amount the difference between the current date and time and the previous stored one. Then, write to the defaults the new updated values, for you to read again the next time your app starts.

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

int timePassed = [[NSUserDefaults standardUserDefaults] intForKey:@"timePassed"];
NSDate *dateOfLastLaunch = [NSDate dateWithString: [[NSUserDefaults standardUserDefaults] stringForKey:@"dateOfLastLaunch"];

//Adds the time passed since the last launch
timePassed += [NSDate timeIntervalSinceDate: dateOfLastLaunch];

//Saves the new values
[defaults setObject:[NSNumber numberWithInt: timePassed] forKey:@"timePassed"];
[defaults setObject:[NSDate date] forKey:@"dateOfLastLaunch"];
luvieere
Ah! UserDefaults, that's what I was trying to remember and couldn't remember what to search for. I had remember hearing it mentioned in the stanford videos but couldn't for the life of me find it again. Thanks!
nullArray
+1  A: 
NSDate *dateOfLastLaunch = [NSDate dateWithString: [[NSUserDefaults standardUserDefaults] stringForKey:@"dateOfLastLaunch"]; 

Where are you getting "dateWithString" on the iPhone?

HelenJ