Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults doesn't save my values

I use this code to save:

[[NSUserDefaults standardUserDefaults] setValue:@"vruch" forKey:@"nastoikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];

and this code to load:

NSString* automanual = [[NSUserDefaults standardUserDefaults] 
                         valueForKey:@"nastroikaIP"];

if ([automanual isEqualToString:@"vruch"]) {
    autovruch.selectedSegmentIndex = 1;
   [self obnovittext];
} 
like image 435
Horhe Garcia Avatar asked May 07 '26 18:05

Horhe Garcia


1 Answers

You should not use the method setValue: (from the NSKeyValueCoding protocol) but setObject: (from the NSUserDefaults class) to store the string.

[[NSUserDefaults standardUserDefaults] setObject:@"vruch" forKey:@"nastroikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];

You can retrieve the string using the method stringForKey:

NSString* automanual = [[NSUserDefaults standardUserDefaults] stringForKey:@"nastroikaIP"];

Finally, note that it is generally better to define constants for the keys you use in NSUserDefaults to avoid any mistyping errors, which may be hard to debug when they happen.

Edit

It looks like you already did a mistyping error nastoikaIP != nastroikaIP. Notice the missing/extra r letter.

like image 93
sch Avatar answered May 10 '26 08:05

sch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!