NSUserDefaults problem
I have this in my app delegate applicationDidFinishLaunching
method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if([defaults objectForKey:@"AcceptTC"] == nil){
NSDictionary *appDefaults = [NSDictionary dictionaryWithObject:@"NO" forKey:@"AcceptTC"];
[defaults registerDefaults:appDefaults];
}
and I have this in my RootViewController viewDidLoad
method:
NSUserDefaults *defaults = [开发者_StackOverflow中文版NSUserDefaults standardUserDefaults];
if(![defaults boolForKey:@"AcceptTC"]){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Notice" message:@"By using this application you agree to be bound by the Terms and Conditions as stated within this application." delegate:self cancelButtonTitle:@"No Deal" otherButtonTitles:@"I Understand",nil];
[alert show];
[alert release];
}
and my alert view delegate does this:
if(buttonIndex == 0){
exit(0);
}
else{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:@"YES" forKey:@"AcceptTC"];
}
However when I click "I understand" (button index 1) and then restart the application I still see the alert view! Even though I've definiely set the value to YES.
I have no idea how to change this. :( I only want it to show the first time a user starts the application - i don't want to keep showing it every time they want to use it.
Thanks
In my application I'm using NSUserDefaults with a bool, works fine.
When the first ViewController loads, it will do:
BOOL terms = [[NSUserDefaults standardUserDefaults] boolForKey:@"termsaccepted"];
if (!terms) {
[self presentModalViewController:disclaimerViewController animated:YES];
}
Within the disclaimer view, after the button has been tapped:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"termsaccepted"];
[[NSUserDefaults standardUserDefaults] synchronize];
I think you're missing the "synchronize" part. However I find using a bool more streamlined, too.
Maybe you need to call synchronize on the defaults to save the changes to disk?
Concering registerDefaults
:
The contents of the registration domain are not written to disk; you need to call this method each time your application starts. You can place a plist file in the application's Resources directory and call registerDefaults: with the contents that you read in from that file.
// Load default defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:[NSDictionary \
dictionaryWithContentsOfFile:[[NSBundle mainBundle] \
pathForResource:@"Defaults" ofType:@"plist"]]];
Code taken from this SO answer.
Another blog article about NSDefaults
:
- http://retrodreamer.com/blog/2010/07/slight-change-of-plan/
精彩评论