views:

197

answers:

3

Hi everybody! 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 informations 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 :(

+1  A: 

Hi,

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

Gjallar
A: 

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!

JJSaccolo
Don't answer your own question to provide more information in this manner. Edit your question instead.
Shaggy Frog
yes. thank you!! :)
JJSaccolo
+2  A: 

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

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

Otherwise you are comparing actual objects rather than their contents.

alku83
If you don't use isEqualToString then you are comparing pointers to objects, not the actual objects.
progrmr
YESSSSSSSSSSSSSSSSSSSSSSSS! :Dsolved!!!!thanks man!!!! really!!!
JJSaccolo
You're welcome, and yes, progrmr is right with his correction.
alku83