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];
Related
I've got an app where I use a JSON based API. As part of JSON, often values are set to "null". This may be common:
{"data":["one","two","three"],"name":null,otherstuff:10}
Recently I've tried to store a misc NSDictionary hierarchy, converted from a JSON object, in NSUserDefaults. Unfortunately it causes an exception if there is null data, converted in IOS to [NSNull null]. Apparently that can't be saved in prefs.
I was wondering if anyone has worked around this before? I tried to add some logic to remove all null values from the JSON first, with limited success, but it seems inappropriate to have to modify the data before storing it. Is there a better way to handle this?
You can first convert your NSDictionary to NSData, then safely store in NSUserDefaults (since NSNull conforms to NSCoding).
//archive
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dictionary];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:#"key"];
//unarchive
NSData *newData = [[NSUserDefaults standardUserDefaults] objectForKey:#"key"];
NSDictionary *newDict = [NSKeyedUnarchiver unarchiveObjectWithData:newData];
Edit: Original data object was being referenced instead of newData object.
I've tried some recursive solutions but they tend to be complicated and don't handle mixed type content well. At the simplest level here is a flat example that works well if you have a predictable, flat response to clean.
NSMutableDictionary *dictMutable = [dict mutableCopy];
[dictMutable removeObjectsForKeys:[dict allKeysForObject:[NSNull null]]];
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 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
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.