NSUserDefaults doesn't save my values - ios

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];
}

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.

Your saving a string so you need to setObject rather than setValue
[[NSUserDefaults standardUserDefaults] setObject:#"vruch" forKey:#"nastoikaIP"];
[[NSUserDefaults standardUserDefaults] synchronize];
and change it for the loading aswell
NSString* automanual = [[NSUserDefaults standardUserDefaults] objectForKey:#"nastroikaIP"];
if ([automanual isEqualToString:#"vruch"]) {
autovruch.selectedSegmentIndex = 1;
[self obnovittext];
}

Related

How to clear NSUserDefaults Data?

When I choose a language from language selection list in my app then it shows that language which I selected previously. If I clear the app from my simulator stack or clear it from xcode then run the project, after that it goes ok, and if I want to change the language again then I faced same problem. My code is given below:
- (IBAction)English:(id)sender {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:[NSArray arrayWithObjects:#"en", nil] forKey:#"AppleLanguages"];
[userDefault synchronize];
ChooseItemVC *civc = (ChooseItemVC*)[self.storyboard instantiateViewControllerWithIdentifier:#"ChooseItemVC"];
[self.navigationController pushViewController:civc animated:YES];
}
Another language selection code:
- (IBAction)Arabic:(id)sender {
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
[userDefault setObject:[NSArray arrayWithObjects:#"ar", nil] forKey:#"AppleLanguages"];
[userDefault synchronize];
ChooseItemVC *civc = (ChooseItemVC*)[self.storyboard instantiateViewControllerWithIdentifier:#"ChooseItemVC"];
[self.navigationController pushViewController:civc animated:YES];
}
The best way to remove all user default vlaues are as follows :
Swift code:
UserDefaults.standard.removePersistentDomain(forName: Bundle.main.bundleIdentifier!)
UserDefaults.standard.synchronize()
Objective C
NSString *strIdentifier = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:strIdentifier];;
[[NSUserDefaults standardUserDefaults] synchronize];
Use following code to remove all existing data in user defaults, i am posting swift code, convert this to objective-c.
if let bundleID = Bundle.main.bundleIdentifier {
UserDefaults.standard.removePersistentDomain(forName: bundleID)
}
To remove use this
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize];
To remove you data from NSUserDefaults
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"AppleLanguages"];
For remove data from NSUserDefaults Try this:
NSString *AppDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:AppDomain];

Objective-C : Can't set NSMutableDictionary from NSUserDefaults

I'm trying to retrieve an NSDictionary that was saved to NSUserDefaults. When I log out what I'm trying to retrieve, it displays correctly:
NSLog(#"%#", [[[NSUserDefaults standardUserDefaults] dictionaryForKey:#"userdetails"] mutableCopy]);
However, when I try to assign to a variable, it returns as nil.
NSMutableDictionary *test123 = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:#"userdetails"] mutableCopy];
Any idea why?
Check with my working code,
Save like this,
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:yourMutableDictionary];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"currentUser"];
[[NSUserDefaults standardUserDefaults]synchronize];
Get dictionary ,
NSData *dictionaryData = [[NSUserDefaults standardUserDefaults] objectForKey:#"currentUser"];
NSDictionary *tempDict = [NSKeyedUnarchiver unarchiveObjectWithData:dictionaryData];
Maybe you can try it use the following code:
[[NSUserDefaults standardUserDefaults] setObject:(NSDictionary *)yourDictionary forKey:yourkey];

NSUserDefault is clearing once the application kills

For Saving the data
NSString *balSnapTokenFromResponce;
balSnapTokenFromResponce = #"456294797493749873";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:balSnapTokenFromResponce forKey:#"Token"];
[defaults synchronize];
For Retreiving the Data
[[NSUserDefaults standardUserDefaults] stringForKey:#"Token"]
This, as shown, makes no sense:
[[NSUserDefaults standardUserDefaults] stringForKey:#"Token"]
You must do something with the return value:
NSString *balSnapTokenFromResponce = [[NSUserDefaults standardUserDefaults] stringForKey:#"Token"];
Perhaps you are, but that's not clear from your question. Because otherwise the code you've posted should work, assuming it's getting called.

call different method with same string in different value

I have two methods in my .m file .And i want to access by different values but in my Facebook variable gives nil value but if i use only one line and remove second line of object for key then it work fine for one method .
How i do this which work for my both methods
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[[NSUserDefaults standardUserDefaults] synchronize];
user=[defaults objectForKey:#"userid"];
facebook=[defaults objectForKey:#"FACEBOOKprofile"];
facebook =[defaults objectForKey:#"VLCC"];
if ([facebook isEqualToString:#"VLCCFACEBOOK"])
{
[self FacebookRecord];
}
else if([facebook isEqualToString:#"VLCC"])
{
[self VlccRecord];
}
assume that
Choice-1
// for accessing the both condition in same time
Initially Store the UserDefault value based on your method.
if you are access with facebook , on that time store the string like
[[NSUserDefaults standardUserDefaults] setObject:"VLCCFACEBOOK" forKey:#"FACEBOOKprofile"];
[[NSUserDefaults standardUserDefaults] synchronize];
if you are access with VLCC , on that time store the string like
[[NSUserDefaults standardUserDefaults] setObject:"VLCC" forKey:#"VLCCprofile"];
[[NSUserDefaults standardUserDefaults] synchronize];
and retrieve the both and check like
if ([[[NSUserDefaults standardUserDefaults]
objectForKey:#"FACEBOOKprofile"]isEqualToString:#"VLCCFACEBOOK"])
{
[self FacebookRecord];
}
if([[[NSUserDefaults standardUserDefaults]
objectForKey:#"VLCCprofile"] isEqualToString:#"VLCC"])
{
[self VlccRecord];
}
Choice-2
// for accessing single condition on single time
if you are access with facebook , on that time store the string like
[[NSUserDefaults standardUserDefaults] setObject:"VLCCFACEBOOK" forKey:#"FACEBOOKprofile"];
[[NSUserDefaults standardUserDefaults] synchronize];
if you are access with VLCC , on that time store the string like
[[NSUserDefaults standardUserDefaults] setObject:"VLCC" forKey:#"FACEBOOKprofile"];
[[NSUserDefaults standardUserDefaults] synchronize];
and retrieve the both and check like
if ([[[NSUserDefaults standardUserDefaults]
objectForKey:#"FACEBOOKprofile"]isEqualToString:#"VLCCFACEBOOK"])
{
[self FacebookRecord];
}
else if([[[NSUserDefaults standardUserDefaults]
objectForKey:#"FACEBOOKprofile"] isEqualToString:#"VLCC"])
{
[self VlccRecord];
}
In your code, the [self VlccRecord] method will always get called because you are overwriting the facebook variable.
facebook=[defaults objectForKey:#"FACEBOOKprofile"];
facebook =[defaults objectForKey:#"VLCC"];
If you are looking to append the two strings : Then use the stringbyAppendingString method.
int a = 10;
a = 20;
print >> a; //20
int a = 10;
print1 >> a; //10
a = 20;
print2 >> a; //20
Here,
a = facebook;
print1 = [self FacebookRecord];
print2 = [self VlccRecord];
I believe you'll understand.

How would I save a UIButton's properties and load with a button? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I save and load the alpha values of a UIButton in an app?
I would like to save the state of the UIButton (e.g. its alpha value and whether it is hidden or not) and this would then load up when the user quits and reloads the app.
I've tried some bits of code with NSUserDefaults but with no luck.
Could somebody help with some sample code so that I can save and load the button's state?
Thanks,
James
Related to Shaharyar's answer (i don't know how to comment):
in this case you need to use NSNumber.
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithFloat:SOME_FLOAT] forKey:KEY];
because float is not an object, but NSNumber is one.
EDITED:
1) To make sure your defaults are created after the application runs at first time:
in your AppDelegate's initialize-method:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithFloat:SOME_FLOAT], #"YOUR_KEY",
nil];
[defaults registerDefaults:appDefaults];
2) Updating defaults after:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setFloat:FLOAT_VALUE forKey:#"YOUR_KEY"];
[prefs synchronize];
3) Read defaults:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
float FLOAT_VALUE = [prefs floatForKey:#"YOUR_KEY"];
Can you post some of the code?
NSUserDefaults is the place to store such information..
Assumption:
Did you make a call to [NSUserDefaults synchronize] after setting the values?
Code:
// Setting a value
[[NSUserDefaults standardUserDefaults] setValue:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
// Getting a value
NSString *var1 = [[NSUserDefaults standardUserDefaults] valueForKey:KEY];
In your case it would be:
// Setting a value
[[NSUserDefaults standardUserDefaults] setFloat:VALUE forKey:KEY];
[[NSUserDefaults standardUserDefaults] synchronize];

Resources