NSUserDefaults problem

≯℡__Kan透↙ 提交于 2019-12-01 12:14:50

问题


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 = [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


回答1:


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/



回答2:


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.




回答3:


Maybe you need to call synchronize on the defaults to save the changes to disk?



来源:https://stackoverflow.com/questions/3759761/nsuserdefaults-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!