Clear data of a particular NSUserDefaults object Data - ios

In my project I am using NSUseDefaults for store data with the different objects.
NSUserDefaults *defaults1=[NSUserDefaults standardUserDefaults];
//---- I have set object for this
[defaults1 synchronize];
NSUserDefaults *defaults2=[NSUserDefaults standardUserDefaults];
//---- I have set object for this
[defaults2 synchronize];
Now I want clear all keys data only for defaults2, not for defaults1. So whenever I am applying below code:
NSDictionary *defaultsDictionary = [defaults2 persistentDomainForName: appDomain];
for (NSString *key in [defaultsDictionary allKeys]) {
NSLog(#"removing user pref for %#", key);
[[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
}
Above code have remove value for defaults2 but also for defaults1. But I don't want to remove objects for defaults1. So please help me out.

NSUserDefaults is like a singelton class so it will always return the same shared system object.
You can store multiple objects using multiple keys and can delete/remove objects against those keys.

If you have read a doc about NSUserDefaults standardUserDefaults you should know that standardUserDefaults Returns the shared defaults object. and actually defaults1 and defaults2 the same.
You can store keys and then delete only those keys like:
NSUserDefaults *defaults1=[NSUserDefaults standardUserDefaults];
//---- I have set object for this
[defaults1 synchronize];
[[defaults1 dictionaryRepresentation] allKeys]; // use this keys for deleting

Related

Setting nested value in NSDictionary that is in NSUserDefaults

I would like to do this:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue#"nextFoo" forKeyPath#"values.foo"];
...
values was shoved into defaults earlier in the code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *values = [NSMutableDictionary alloc] init];
[values setObject#"firstFoo" forKey:#"foo"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:values forKey:#"values"];
I am guessing that regardless of the fact that I shoved a Mutable Dictionary into user defaults it gets stored as an immutable dictionary. I am trying to take a shortcut to allow me set a nested value without getting the values dictionary as mutable, setting the value there and then setting values again, i.e. longer version that I am trying to get around
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *values = [[defaults objectForKey:#"values"] mutableCopy];
[values setObject#"nextFoo" forKey:#"foo"];
[defaults setObject:values forKey:#"values"]; // set the entire values dictionary again, even though I really only needed to set one nested value
It's a common mistake, but you need to use the setObject: methods for NSUserDefaults, not setValue: and so the setValue:forKeyPath: also won't be of help to you. You'll need to just fetch the dictionary out and set the value then re-set the dictionary.

nsuserdefault has key-values set how to delete it?

I have already tried to delete all the key-values pair when the app starts and again when i check keys these keys are saved in NSUserDefault. I have these preferences stored.
NSArray *keys = [[[NSUserDefaults standardUserDefaults] dictionaryRepresentation] allKeys];
NSLog(#"all keys %#", keys);
keys (
NSLanguages,
AppleITunesStoreItemKinds,
AppleLocale,
AppleLanguages,
NSInterfaceStyle
)
When I store new dynamic values to the NSUserDefaults, I want to select all the keys except these preferences.
Please help me with this problem.
Thanks in advance
Don't do what you're trying to do. Don't tamper with any of the keys added by Apple. Keep your own set of keys (preferably with prefixes on the names) and edit only those.
Generally you shouldn't delete keys unless there is some specific requirement in your app to do so. What you should do is to set default values for each of your keys when the app starts:
[[NSUserDefaults standardUserDefaults] registerDefaults:#{... : ...}];
These defaults will be valid while the app is running but won't be saved. If you set anything using any of the set...:forKey: methods and synchronize then they will overwrite the defaults and be saved.
Try this
- (NSDictionary *) dictionaryRepresentation. Using this method on the standard user defaults, you can get a list of all keys in the user defaults. You can then use this to clear the user defaults:
NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
NSDictionary * dict = [defs dictionaryRepresentation];
for (id key in dict) {
[defs removeObjectForKey:key];
}
[defs synchronize];
removeObjectForKey -- that should give you the ability to remove a preference.
You can remove everything in NSUserDefaults associated with your app by calling this.
// remove entire user defaults
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
[[NSUserDefaults standardUserDefaults] synchronize]; // not sure if needed, but never hurts
This should give you a clean slate for saving information to user defaults.

iOS: Storing selected table view rows in userDefaults

In my app I have a tableview which allows user to enable or disable elements by tapping the rows. Quite simply, I need to store each row's condition in userDefaults - if it's turned on, or not. How would I go about this?
I was thinking I could add a BOOL property to the object each row represents for whether or not its enabled but how would I go about doing remembering the value of the property for each individual object?
You could use some kind of id on each row to be able to identify a particular row. Then you could create an custom object and store it in NSUserDefaults.
Look at this so question
You can just create a bunch of setting keys:
// SET
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:YES forKey:#"setting1_ON"];
[defaults setBool:NO forKey:#"setting2_ON"];
// GET
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
bool setting1 = [defaults boolForKey:#"setting1_ON"];
bool setting2 = [defaults boolForKey:#"setting2_ON"];
Or store one array of all settings (or dictionary):
// SET
NSMutableArray *settings = [NSMutableArray array];
for (UITableViewCell *c in [self.tableView subviews]) {
if (c.selected) {
[settings addObject:[NSNumber numberWithBool:YES]];
} else {
[settings addObject:[NSNumber numberWithBool:NO]];
}
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:settings forKey:#"settings"];
// GET
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableArray *mySettings = (NSMutableArray *)[defaults objectForKey:#"settings"];
setting1 = [mySettings objectAtIndex:1];
setting2 = [mySettings objectAtIndex:2];
On that note, you might consider 2 other options... 1. Just keep all your BOOLs in an array instead of adding them to the cells, then store it when needed; 2. Create a NSObject that is your settings, keep them all in there, and then store the entire object:
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:myApp.settings];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myEncodedObject forKey:#"settings"];
To do this you have to add encode/decode stuff to that settings object... there's more on storing custom objects around these parts.

Save NSArray to NSUserDefaults issues (using custom object in array)

I try to save my object to NSUserDefaults. But when I call this method again it is not have any info about previous operation.
There is my method below:
- (void)addToCart {
if([[NSUserDefaults standardUserDefaults] objectForKey:kCart]) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *products = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:kCart]];
[products addObject:self.product];
[prefs setObject:products forKey:kCart];
[prefs synchronize];
[products release];
}
else {
//Saving...
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSArray arrayWithObjects:self.product, nil] forKey:kCart];
[prefs synchronize];
}
}
I need to save a collection with a products to NSUserDefault. I wrap my object to NSArray and save it but it doesn't work.
Everything put into NSUserDefaults must be a valid property list object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary). All collection elements must themselves also be property list objects.
In order to save non-PL objects into NSUserDefaults, you must first convert the object into a PL object. The most generic way to do this is by serializing it to NSData.
Serializing to NSData is handled with NSKeyedArchiver. See Storing NSColor in User Defaults for the canonical example of this. (That document is very old and still references NSArchiver which will work fine for this problem, but NSKeyedArchiver is now the preferred serializer.)
In order to archive using NSKeyedArchiver, your object must conform to NSCoding as noted by #harakiri.
You need to conform to the <NSCoding> protocol and implement -initWithCoder: and -encodeWithCoder: in your custom object.
See: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

NSMutableArray stored in NSUserDefaults won't save data

When a user signs in through my iPhone app, I create a bunch of default elements in the NSUserDefaults. One of these is an NSMutableArray that I add the following way:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *theArray = [NSMutableArray array];
[prefs setObject:theArray forKey:#"theArray"];
This works flawlessly. However, when I want to insert or retrieve values from theArray, something goes wrong. Here's an excerpt from another file in my app:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[[prefs objectForKey:#"theArray"] setValue:#"This is a value" forKey:#"aValue"];
NSLog(#"%#", [[prefs objectForKey:#"theArray"] valueForKey:#"aValue"]);
I would expect to see "This is a value" in the console when the code has run, but instead I get this:
2011-08-08 18:35:17.503 MyApp[7993:10d03] (
)
How come the array is empty? I've tried the same thing using an NSArray with the same result.
When you store mutable objects to NSUserDefaults, it stores an immutable copy of it so you can't change it directly like that. You have to get the mutable copy out of defaults, change it, and then set it back, replacing old object in defaults.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *mutableArrayCopy = [[prefs objectForKey:#"theArray"] mutableCopy];
[mutableArrayCopy addObject:#"some new value"];
[prefs setObject:mutableArrayCopy forKey:#"theArray"];
[mutableArrayCopy release];
NSArray *savedArray = [NSArray arrayWithObjects:#"obj1",#"obj2",#"obj3", nil];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:savedArray forKey:#"key_for_savedArray"];
[userDefaults synchronize];
//To retrive array use:
NSArray *retrivedArray = [userDefaults objectForKey:#"key_for_savedArray"];

Resources