App crashing during NSUserDefault data removal - ios

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

Related

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

how to clear all NSUserDefaults values in objective-C? [duplicate]

This question already has answers here:
Clearing NSUserDefaults
(15 answers)
Closed 7 years ago.
I am using NSUserDefaults lots of time in my app to store some values, but on "refresh button" i want to clear all stored values, Is there any way to clear all NSUserDefaults values?
You can remove all stored value using below code see here for more details
- (void)removeUserDefaults
{
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [userDefaults dictionaryRepresentation];
for (id key in dict) {
[userDefaults removeObjectForKey:key];
}
[userDefaults synchronize];
}
Or in shortest way
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
Swift
let defaults = UserDefaults.standard
defaults.dictionaryRepresentation().keys.forEach { (key) in
defaults.removeObject(forKey: key)
}
You can clear your user defaults by using following statements -
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
You can call a selector on the refresh button and keep the above statements in it, as-
- (void) refreshUserDefaults
{
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
}

NSUserDefaults overriding previously saved values

I have two completely separate tasks being carried out but somehow they seem to connect.
In ViewController 1, I have:
NSString *foo = #"foo";
NSUserDefaults *default1 = [NSUserDefaults standardUserDefaults]
[default1 setObject:foo forKey:#"foo"];
[default1 synchronize];
and when I do:
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"foo"]);
The value printed is what I expect it to be.
In ViewController 2, I have:
NSString *bar = #"bar";
NSUserDefaults *default2 = [NSUserDefaults standardUserDefaults]
[default2 setObject:bar forKey:#"bar"];
[default2 synchronize];
And same again when I NSLog it, the value is what I expect it to be.
But somehow when i try to print object #"foo" again it gives me the value for the second object, in this case #"bar"
Any guidance on why my original value is being overridden by the second value even tough the variable/key names are different in the 2 classes?
You are doing this for both:
[foo setObject:bar forKey:#"bar"];
Shouldn't it be:
[defaults1 setObject:foo forKey:#"foo"];
And
[defaults2 setObject:bar forKey:#"bar"];
There is however, a greater problem:
NSString *foo = #"foo";
NSUserDefaults *default1 = [NSUserDefaults standardUserDefaults];
[default1 setObject:foo forKey:#"foo"];
[default1 synchronize];
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"foo"]);
NSString *bar = #"bar";
NSUserDefaults *default2 = [NSUserDefaults standardUserDefaults];
[default2 setObject:bar forKey:#"bar"];
[default2 synchronize];
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"bar"]);
Will work properly, however you're creating defaults1 and defaults2 which are both instances of standard defaults, so:
NSUserDefaults * defaults1 = [NSUserDefaults standardUserDefaults];
NSUserDefaults * defaults2 = [NSUserDefaults standardUserDefaults];
[NSUserDefaults standardUserDefaults];
Are all pointers to the standardUserDefaults singleton. So they are identical instances. You could simply do:
NSUserDefaults *standardDefaults = [NSUserDefaults standardUserDefaults];
NSString *foo = #"foo";
[standardDefaults setObject:foo forKey:#"foo"];
NSString *bar = #"bar";
[standardDefaults setObject:bar forKey:#"bar"];
[standardDefaults synchronize];
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"foo"]);
NSLog(#"%#", [[NSUserDefaults standardUserDefaults] objectForKey:#"bar"]);
You can print out the entire set of user defaults with code like this
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *dictionary = [defaults dictionaryRepresentation];
NSLog( #"%#", dictionary );
Note that Apple puts lots of garbage in the user defaults, so you'll have to scroll to the end to see foo and bar. I'm guessing that you have a typo in code that you haven't shown us, and either foo is being overwritten, or foo simply isn't being displayed properly.
The current code in your question (after 1 edit) is all good and should work correctly.

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 Contains Value Or Not?

How to know whether NSUserDefaults contains any value?How to check whether its empty?
There isn't a way to check whether an object within NSUserDefaults is empty or not.
However, you can check whether a value for particular key is nil or not.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSObject * object = [prefs objectForKey:#"your_particular_key"];
if(object != nil){
//object is there
}
NSUserDefaults *data = [NSUserDefaults standardUserDefaults];
NSString *string = [data objectForKey:#"yourKey"];
if(string==nil)
NSlog(#"nil")
Take a look at NSUserDefault documentation
// For saving the values
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
// saving an NSString
[userDefaults setObject:#"Ttest" forKey:#"key"];
// --- For Retrieving
NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [userDefaults stringForKey:#"key"];
To check whether a specific value is set or not, no matter of its location (global or application's), check the returned value of -[NSUserDefaults objectForKey:]
id obj = [[NSUserDefaults standardUserDefaults] objectForKey:#"My-Key-Name"];
if (obj != nil) {...}
To check if the application (bundle) has any settings stored in user defaults:
NSUserDefaults* sdu = [NSUserDefaults standardUserDefaults];
NSString* bundleId = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary* mainBundleSettings = [sdu persistentDomainForName:bundleId];
NSLog(#"%#", mainBundleSettings);
If you are interested in all possible values for which -[NSUserDefaults objectForKey:] will return something, including system global settings, simply call
NSDictionary* allPossibleSettings = [sdu dictionaryRepresentation];
NSUserDefaults is never empty. It combines global settings, bundle's settings, temporary data and maybe something else. For example, if you call:
[[NSUserDefaults standardUserDefaults] objectForKey:#"NSBoldSystemFont"]
you will get the #"LucidaGrande-Bold" string value which will be taken from global settings, even when your application has never set this value.

Resources