All I want is an integer which e开发者_如何学Pythonverytime my app opens is incremented by one. Is there an easy way to do this? Please help.
Thanks, in advance.
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"];
Store the integer in NSUserDefaults
. The documentation is here.
While you could use NSUserDefaults
this way 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 available with a quick search), which should get you started.
精彩评论