views:

58

answers:

3

All I want is an integer which everytime my app opens is incremented by one. Is there an easy way to do this? Please help.

Thanks, in advance.

+1  A: 

Store the integer in NSUserDefaults. The documentation is here.

Elfred
+1  A: 

You will want to do something like this:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger counter = [defaults integerForKey:@"counterKey"];
counter++;
[defaults setInteger:counter forKey:@"counterKey"];

This also works if the key has never been registered. integerForKey will just return 0, which is actually what we want. However, if you want to be extra-secure, you can check it beforehand. after the second line by something like this:

NSInteger counter = 0;
if ([defaults objectForKey:@"counterKey"] != nil)
    counter = [defaults integerForKey:@"counterKey"];
Max Seelemann
thats so helpful thanks. One more question, is the integers default value zero in the standardUserDefaults?
SammmyC
The reason I ask is I want the integer to be zero the first time I open it, and to increment it on each subsequent opening.thx
SammmyC
You would need to register the value 0 before you read in the value using the code above. Check out the documentation for:- (void)registerDefaults:(NSDictionary *)dictionary
Joe Ibanez
If the key does not exist yet integerForKey will return 0. So there is no IMMEDIATE need to register it beforehand, the code will just work.I adjusted the example such that it shows how to do the check.
Max Seelemann
thanks that was really helpful
SammmyC
A: 

While you could use NSUserDefaults this way it isn't the most elegant solution. Defaults are a place to keep application settings not application data. A good guideline is to think of your data item as appearing in your app's settings and whether it is valid there. In your case the number of times the app has been opened is not a user setting; it isn't something that the user will be able to change, is it?

A better way would be to write the data to a plist, which is a simple and fast way of storing application data. Have a look at the instructions here for example (there are others), which should get you started.

Abizern