开发者

NSUserDefaults doesn't save

i'm trying to save some informations in an iphone/ipad app. The problem is that it works but if i close the app (with the home button on the simulator or closing with cmd+q) the informat开发者_运维技巧ions become lost!

this is my code (and, if you see, i used "syncronize")

- (IBAction)choose1{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"choose1" forKey:@"choose"];
    [defaults synchronize]; 
}

- (IBAction)choose2{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"choose2" forKey:@"choose"];
    [defaults synchronize];
}

- (IBAction)openview{
    NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:@"choose"];
    if (var == @"choose1"){
        [self pushViewController:view1 animated:YES];}
    else if (var == @"choose2"){
        [self pushViewController:view2 animated:YES];
    }

}

I don't understand why :(


When comparing strings, you should use the isEqualToString method, ie:

if ([var isEqualToString:@"choose1"]){

Otherwise you are comparing actual objects rather than their contents.


I am not entirely sure, but maybe it is saving your defaults and the error is located somewhere else. I am thinking about your "openView" method:

- (IBAction)openview{
NSString *var = [[NSUserDefaults standardUserDefaults] objectForKey:@"choose"];
if (var == @"choose1"){
    [self pushViewController:view1 animated:YES];}
/** you are comparing to "choose1" here as well. **/
else if (var == @"choose1"){
    [self pushViewController:view2 animated:YES];
}

Another possibilty might be that you never call your choose1() or choose2() methods? This would explain why the value is never changed.

Despite from these 2 possibilites I think there is no error in the code you use to change the UserDefaults.

Hope this helps.

Regards,

Gjallar


ah, i'm sorry: i'm italian so i used the word "choose" with the italian translation "scelta". Here i translated in english and i wrote "choose1" but in my code i used "choose2" (or "scelta2" :P)

for the other possibility (that i've never called the function choose1() or choose2() )... no, i've called, of course!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜