I am currently saving array with custom objects using archiever
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cache];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"KP_SEARCH_CACHE"];
[[NSUserDefaults standardUserDefaults]synchronize];
But the order of the objects when I retrieve the array is random. i need to retain the original order. It would be of great help if someone could recommend something
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];
After reading from various answers I have come to know that NSUserDefaults can save multiple datatypes for one key. But what I cannot find is if
[NSUserDefaults standardUserDefaults] removeObjectForKey:"someKey"];
removes all objects of all data types associated with that key?
You cannot store different kind of objects for one key.
If you set an object for a key it will erase the old one.
But, if your are searching for a way to store multiple data for one key, you can store a NSDictionary.
Ex :
MyObject *obj = [[MyObject alloc] init];
NSString *otherType = #"mystring";
NSDictionary *multipleData = #{ #"key1" : obj , #"key2" : otherType}
[[NSUserDefaults standardUserDefaults] setObject: multipleData forKey:#"multipleData"];
[[NSUserDefaults standardUserDefaults] synchronize];
And if you want to remove it :
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"multipleData"];
[[NSUserDefaults standardUserDefaults] synchronize];
Yes it does.
Your data may be anything an array or dictionary or simple int. This command will remove that data.
As iPatel suggested. You need to call:
[[NSUserDefaults standardUserDefaults] synchronize];
After adding or deleting any data. Hope this helps.. :)
You cannot store multiple objects under one key. NSUserDefaults acts just like a NSDictionary. When you set an object for a specific key you overwrite the old object. So removeObjectForKey: just removes one object/value; the one you had stored under that key.
Do you call
[[NSUserDefaults standardUserDefaults] synchronize];
after delete all the data of the key and also might be you can not store multiple data on single key, it's return new one that inserted to last. ?
Read official documentation of removeObjectForKey of NSUserDefaults.
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
NSString *yourDomain = [[NSBundle mainBundle] bundleIdentifier];
[userDefault removePersistentDomainForName:yourDomain];
Here. if u want to reset.
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'm trying to add elements to an NSMutableArray whenever a user selects a country. But each time I use [myarray setobject:#""];, it's adding the new value, overwriting my old value. I want this array as I'm using it in:
[[NSUserDefaults standardUserDefaults]setObject:(NSMutableArray *)selectedCountriesByUser forKey:#"userSelection"];
[[NSUserDefaults standardUserDefaults]synchronize];
I want an array which maintains the list of countries selected by the user even after the application is closed.
What should I do?
setObject replace all objects in array
for example, get value from NSUserDefault:
NSMutableArray *myMutableArray = [NSMutableArray arrayWithArray:[[NSUserDefault standardUserDefault] objectForKey:"userSelection"]];
you should use [myMutableArray addObject:"aCountry"]; without overwriting, but adding only
and after
[[NSUserDefaults standardUserDefaults]setObject:myMutableArray forKey:#"userSelection"];
[[NSUserDefaults standardUserDefaults]synchronize];
EDIT:
-(void) viewDidLoad {
//your selectedCountriesByUser
myMutableArray = [NSMutableArray arrayWithArray:[[NSUserDefault standardUserDefault] objectForKey:"userSelection"]];
}
...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//add object to array
[myMutableArray adObject:"yourObj"];
[[NSUserDefaults standardUserDefaults]setObject:myMutableArray forKey:#"userSelection"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
You're asking two different things. First, -setObject: is not a NS(Mutable)Array method. You are probably looking for the -addObject: method. So, to add an object to your NSMutableArray, you need to do:
[myMutableArray addObject:yourObject]
//Remember that `-addObject` is present only in NSMutableArray, not in NSArray
The second thing you are trying to achieve is to store the array in NSUserDefaults. to do so, after you add the object to the array you want, you should be fine do to so:
[[NSUserDefaults standardUserDefaults] setObject:myMutableArray forKey:#"userSelection"];
[[NSUserDefaults standardUserDefaults] synchronize];
// ARRAY DECLARATION AND ASSIGNMENT OF VALUES TO IT
NSMutableArray * selectedCountriesByUserArray=[[NSMutableArray alloc] init];
[selectedCountriesByUserArray addObject:#"value1"];
[selectedCountriesByUserArray addObject:#"value2"];
[selectedCountriesByUserArray addObject:#"value3"];
// STORING AN ARRAY WITH THE KEY "userSelection" USING NSUSERDEFAULTS
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:selectedCountriesByUserArray forKey:#"userSelection"];
[defaults synchronize];