I want to add the another object to existing key in NSUserDefault.
I try this code to add in NSUserDefault.
delegate.str=[first objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str);
delegate.str1=[details1 objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str1);
[delegate.BookMarkDefault setObject:delegate.str forKey:#"Name"];
// BookMarkDefault This is NSUSERDefault.
First I will insert delegate.str value value successfully goes to NSUSerDefault, but when next time adding new value through delegate.str for key under Name will replace previous value. I want to add new value under the same Key.
This is not possible if you want to fullfill this kind of requirement then try to use array and then put that array into NSUSerDefault...
Try this code
delegate.str=[first objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str);
delegate.str1=[details1 objectAtIndex:delegate.selectId];
NSLog(#"%#",delegate.str1);
[yourarray addObject:delegate.str];
NSLog(#"%#",delegate.Bookmarknamearray);
[delegate.BookMarkDefault setObject:youarray forKey:#"Name"];
No its not possible to assign multiple values to same key. If you want to use multiple values to same key then use array or dictionary and assign them to the key.
Ex :
[[NSUserDefaults standardUserDefaults] setObject:YOUR_ARRAY forKey:#"Name"];
Hope it helps you.
You can't save two objects for same key.In NSUserDefaults and NSDictionary keys will be unique (There can be only one object for a particular key).
If you need to do this, you can store the values in NSMutableArray or NSDictionary and add that to the NSUserDefaults like:
[[NSUserDefaults standardUserDefaults] setObject:dataArray forKey:#"Name"];
It may be helpful
[[NSUserDefaults standardUserDefaults] setObject: delegate.str forKey:#"Name"];
You can not assign two value in single key of NSUserDefaults, you must need to take another "KEY" for each value . your can replace pervious value by using following code :
Just try with following code :
[[NSUserDefaults standardUserDefaults] setObject: delegate.str forKey:#"Name"];
EDITE:
But you can add array in NSUserDefaults, suchlike
self.golbalArr = [[NSMutableArray alloc]initWithObject:#"1", #"2",....,nil];
[[NSUserDefaults standardUserDefaults] setObject: self.golbalArr forKey:#"Name"];
Related
I am trying to save an array of objects into an NSUserDefault without success. When I log out the array before the attempt it is full of object. However, when I try to log out the NSUserDefault it is NULL. Can anyone see what I might be doing wrong? Thanks for any suggestions:
Items *myItems = [mutableFetchedObjects mutableCopy];
NSLog(#"my Items%#",myItems);//LOGS OUT LONG LIST OF ITEMS
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myItems];
[currentDefaults setObject:data forKey:#"myItems"];
[currentDefaults synchronize];
Items *myRetrievedItems = [[[NSUserDefaults standardUserDefaults] arrayForKey:#"myItems"] mutableCopy];
NSLog(#"my Retrieved Items%#",myRetrievedItems); //LOGS OUT AS NULL
As the other answers mentioned, it is because your array is not complying to the NSDictionary types (string, binary, bool, etc). Your members of array is of custom types therefore it cannot be saved. What you need to do is convert your array to binary first and then save it.
You have to unarchive your data first at the time of retrieving back. You are directly accessing the data. This won't work. You can do it the similar way you are archiving the data
NSData *dataObj = [currentDefaults objectForKey:#"myItems"];
Items *myRetrievedItems = [NSKeyedUnarchiver unarchiveObjectWithData:dataObj];
For more reference, you can consider this answer.
Hope this helps.
Thanks!
Your access value method is wrong.
You can get the array in following code:
Items *myRetrievedItems = [[[NSUserDefaults standardUserDefaults] objectForKey:#"myItems"] mutableCopy];
I would like to remove an NSDictionary that is stored in NSUserdefaults.
I tried with this :
[NSUserDefaults removeObjectForKey:#"bookmarks"];
But, all my favorites are removed
How can I delete one single favorite?
I found the same question here
- Remove object of NSUserDefault by tableview cell
thanks all
Get the dictionary of bookmarks, creating a mutable copy, so you can modify it:
NSMutableDictionary *bookmarks = [[userDefaults objectForKey:#"bookmarks"] mutableCopy];
Remove the one you want:
[bookmarks removeObjectForKey:#"Bookmark be gone"];
Put the bookmarks back:
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
and sync:
[userDefaults synchronize];
EDIT Following a comment from the OP, it sounds like it might be in an array, rather than a dictionary. The principle is the same:
Get the array of bookmarks, creating a mutable copy, so you can modify it:
NSMutableArray *bookmarks = [[userDefaults objectForKey:#"bookmarks"] mutableCopy];
Remove the one you want (to find the index of the object you probably need to iterate the array. See this question):
[bookmarks removeObjectAtIndex:5];
Put the bookmarks back:
[userDefaults setObject:bookmarks forKey:#"bookmarks"];
and sync:
[userDefaults synchronize];
I have an array which saves all the user inputs as an array of Strings using NSUserDefaults. In another view controller this array data can be viewed in a UITableView. Is there any way to delete the record in the array when I delete a row in the UITableView?
please refer the following for more detail.
https://stackoverflow.com/questions/32679088/tableview-nsinternalinconsistency-exception-error
Thanks
try like this in your tableview delete function
NSMutableArray *dataArray = [[NSUserDefaults standardUserDefaults] valueForKey:#"SavedArray"];
[dataArray removeObjectAtIndex:yourIndex];
[[NSUserDefaults standardUserDefaults ] setValue:dataArray forKey:#"SavedArray"];
[[NSUserDefaults standardUserDefaults]synchronize];
Using this code you will delete or resave your array in userdefaults
In your didSelect
NSMutableArray *yourArray=[[NSMutableArray alloc]init];
[yourArray removeObjectAtIndex:indexPath.row];
[self.tableView reloadData];
This is a three step process:
Step 1: Fetch & save your user details in a mutable array:
NSMutableArray *userDetailsArray = [[[NSUserDefaults standardUserDefaults] objectForKey:#"userDetails"] mutableCopy];
Step 2: Update your data array once user delete something. Use any of the below methods:
[userDetailsArray removeObject:<Your_Object>];
[userDetailsArray removeObjectAtIndex:<Your_Index>];
Step 3: Finally save them back in NSUserDefaults:
[[NSUserDefaults standardUserDefaults] setObject:userDetailsArray forKey:#"userDetails"];
[[NSUserDefaults standardUserDefaults] synchronize];
If you want to delete all NSUser defaults just use :-
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(NSBundle.mainBundle().bundleIdentifier!)
Based on Apple documentation NSUserDefaults Class Reference "Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you set a mutable string as the value for "MyStringDefault", the string you later retrieve using stringForKey: will be immutable"
I am trying to save a NSDictionary with array values to NSUserDefaults but am having some strange trouble.
My NSDictionary has NSStrings for keys and each value is a NSArray of NSNumbers. When I print the dictionary out, everything is fine. I write this dictionary to NSUserDefaults and if I read it back out right away, everything seams fine. Using this everything seams just fine:
[[NSUserDefaults standardUserDefaults] setObject:self.selectedOptionPositions
forKey:PREF_OPTIONS_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
//THIS PRINT EVERYTHING OUT EXACTLY AS IT SHOULD!
NSLog(#"read after write: %#", [[NSUserDefaults standardUserDefaults]
objectForKey:PREF_OPTIONS_KEY]);
The problem comes when I create a new instance of the class that handles this. When I make a new instance of the class and in the init method check the NSDictionary like so:
NSLog(#"read initial: %#", [[NSUserDefaults standardUserDefaults]
objectForKey:PREF_OPTIONS_KEY]);
When I print that logging, the NSDictionary contains all of the keys but all of the values are now empty! All newly added keys exist after recreating the class, but no values persist.
What could be wrong here? There are no warnings or errors in the console.
Try this:
You can use NSKeyedArchiver to write out your dictionary to an NSData, which you can store among the preferences.
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.selectedOptionPositions];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:PREF_OPTIONS_KEY];
For retrieving data:
NSData *dictionaryData = [defaults objectForKey:PREF_OPTIONS_KEY];
NSDictionary *dictionary = [NSKeyedUnarchiver unarchiveObjectWithData:dictionaryData];
As in the iOS Developer Documentation for NSKeyedArchiver it says that:
NSKeyedArchiver, a concrete subclass of NSCoder, provides a way to
encode objects (and scalar values) into an architecture-independent
format that can be stored in a file. When you archive a set of
objects, the class information and instance variables for each object
are written to the archive. NSKeyedArchiver’s companion class,
NSKeyedUnarchiver, decodes the data in an archive and creates a set of
objects equivalent to the original set.
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.