开发者

AppDelegate int value keeps getting reset

开发者 https://www.devze.com 2023-03-25 04:06 出处:网络
In my project AppDelegate file, I have an int d开发者_如何学JAVAeclared called correctAnswersCountR1. So in the app they take a small quiz and that variable keeps track of how many correct answers the

In my project AppDelegate file, I have an int d开发者_如何学JAVAeclared called correctAnswersCountR1. So in the app they take a small quiz and that variable keeps track of how many correct answers they got. Now somewhere else in the project I use this variable like so:

int r1score=appDelegate.correctAnswersCountR1;

The problem is that apparently if I exit the app and come back, the value isn't remembered, and is set back to its default value. How can I store this number so that it is remembered if the user closes the app and comes back?


You can use NSUserDefaults to store your value:

**Saving**
//Do this right before the app exits
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];

// This is suggested to synch prefs, but is not needed
[prefs synchronize];

**Retrieving**
//Do this when your app is loaded again
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];


You could set up core data for your project, though unless you plan on storing more information persistently for your app Core Data might be a bit of overkill. You could also try writing it to a file and just reading it on load.

Edit: For this specific scenario Oscar's answer seems more appropriate, though depending on where you plan on going with your app, CoreData or a file may be a good choice.


You'll want to do some research about NSUserDefaults.

Here is the apple documentation

On another note it's not considered best practice to store data in the AppDelegate


You have to use a preferences storing mechanism. I'm not all too familiar with the iPhone toolkit, but on Mac OS X and Cocoa there's NSUserDefaults. When your app launches, you would load the value from the user defaults (preferences) through [[NSUserDefaults standardUserDefaults] intForKey:@"count"], and whenever the value changes, you would call [[NSUserDefaults standardUserDefaults] setInt:answerCount... forKey:@"count"].


I'm pretty sure that you want to write the value into a file to make it persistent.

This is because an application which moved to the background might be terminated for example if the system measures out that it needs some more memory.

So it kills the application and restarts it when the user switches over.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号