Objective-C : Can't set NSMutableDictionary from NSUserDefaults - ios

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

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

App crashing during NSUserDefault data removal

When I call this function my app gets crash.
I got this error : [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[1].
How i can resolve it please help if you know.
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [defs dictionaryRepresentation];
for (id key in dict)
{
NSObject * object = [dict objectForKey:key];
if(object != nil)
{
[defs removeObjectForKey:key];
[defs synchronize];
}
}
Kindly use following code. It should help you
NSString *applicationDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:applicationDomain];
You can also use
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
for (NSString *key in [defaultsDictionary allKeys]) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
[[NSUserDefaults standardUserDefaults] synchronize]; //outside loop.
NOTE: The crash which you are mentioning is regarding setValue ForKey in a Dictionary. Kindly user breakpoint and see where you are inserting nil value in Dictionary.
try adding the keys of the desired entries into NSArray inside the loop
then do removeObjectsForKeys:array outside the loop
It's preferable to not remove entries while enumerating inside a for loop
My solution for your question is
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
NSDictionary *dict = [userDefaults dictionaryRepresentation];
for (id key in dict) {
[dict removeObjectForKey:key];
}
[defs synchronize];

How to store JSON response in string and then store that string locally ios objective c

[enter image description here][1]I get three values from JSON. How do I store those three values in NSString and then store those strings locally i.e on the device?
I tried NSUserDefaults but I'm unable to do it. I've attached the code snippet.
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:responseObject
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! JSONData)
{
NSLog(#"Got an error: %#", error);
} else {
//_branchId = [responseObject valueForKey:#"branchId"];
_branchName = [responseObject valueForKey:#"branchName"];
_branchUri = [responseObject valueForKey:#"branchUri"];
[[NSUserDefaults standardUserDefaults] setObject:_branchId forKey:[responseObject valueForKey:_branchId]];
[[NSUserDefaults standardUserDefaults] setObject:_branchName forKey:#"branchName"];
[[NSUserDefaults standardUserDefaults] setObject:_branchUriStore forKey:#"_branchUri"]; // Here the setobject value remains nil only
[[NSUserDefaults standardUserDefaults] synchronize];
PS: I want to use that stored value in my commonutility also. How to do that as well?
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"(__fetchBranchUri)/%#",url]]];
In the else block replace the contents with
[[NSUserDefaults standardUserDefaults] setObject:[responseObject valueForKey:#"branchId"] forKey:#"branchId"];
[[NSUserDefaults standardUserDefaults] setObject:[responseObject valueForKey:#"branchName"] forKey:#"branchName"];
[[NSUserDefaults standardUserDefaults] setObject:[responseObject valueForKey:#"branchUri"] forKey:#"_branchUri"];
[[NSUserDefaults standardUserDefaults] synchronize];
Edit: Explanation
In your code above the object _branchUriStore is not defined, and may be part of your problem (a simple typo?). Below, I have updated and condensed your code to remove another problem with your usage of branchId and so that you might recognize from the style that much of what you were trying to do is fine.
Also note that #rmaddie has provided additional refinements below in the comments.
Okay here is what you should do.
1- convert your JSONData no NSData
2-Save your NSData in the NSUserDefaults/
Hope this helps!

Saving NSMutableDictionary containing UIButtons in the NSUserDefults

I am trying to save a NSMutableDictionary containing UIButtons in the NSUserDefults in this way:
[UserFolderDictionary setObject:FolderButton forKey:[NSString stringWithFormat:#"%ld", (long)numberFinal]];
[[NSUserDefaults standardUserDefaults] setObject:UserFolderDictionary forKey:#"UserFolderDictionarySaved"];
The app crashes with the error 'attempt to insert non-property list object'. To re-catch it I tried this:
NSMutableDictionary* UserFolderDictionary = [[[NSUserDefaults standardUserDefaults] dictionaryForKey:#"UserFolderDictionarySaved"] mutableCopy];
FolderButton is a normal UIButton with a tag and a background image.
You can't save buttons in NSUserDefaults, and furthermore you SHOULDN'T save buttons in NSUserDefaults.
Buttons are view objects, not model objects. You should save state information from your buttons, and then use that information to recreate your button.
You may try this.
`
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[myDictionary setObject:button forKey:#"myBtn"];
//save nsdata
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myDictionary];
[userDefaults setObject:data forKey: #"SavedBtn"];
[userDefaults synchronize];
//now retrieve it
NSData *data1 = [userDefaults objectForKey:#"SavedBtn"];
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
`
Hope that Helps!

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

Resources