How to read an Array stored in NSUserDefaults? - ios

Im storing a NsMutableArray in Nsuserdefaults, I think this can be done and its correct, so Im adding a text from a TexField to the Array but when I try to read it in a NSLOG sends null, heres the code:
#property(nonatomic, strong)NSMutableArray *tasks;
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:self.tasks forKey:#"tasks"];
[self.tasks addObject:textField.text];
NSLog(#"tasks:%#", [[NSUserDefaults standardUserDefaults]objectForKey:#"tasks"]);
Thanks!!

You need to add the text to the array BEFORE you save it to defaults
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
// make sure self.tasks is initialized
if (!self.tasks) self.tasks = [NSMutableArray new];
// add object first
[self.tasks addObject:textField.text];
// now save array
[standardUserDefaults setObject:self.tasks forKey:#"tasks"];
NSLog(#"tasks:%#", [[NSUserDefaults standardUserDefaults]objectForKey:#"tasks"]);
If this is returning null, then

Related

NSMutableArry not getting added into NSuserdefaults

I am try to add a NSMutableArray into the NSUserDefault but it is always retuning null.
I know that .so I'm even creating a mutable copy os array as well but still.
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.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *myStoredEvents=[prefs objectForKey:#"MySavedEvents"];
NSMutableArray *myStoredEventsNew=[[NSMutableArray alloc]init];
myStoredEventsNew=myStoredEvents;
NSMutableArray *tempDic=[myevents objectAtIndex:eventId];//myevents a NSMutableArray
if(myStoredEventsNew != nil)
{
[myStoredEventsNew insertObject:tempDic atIndex:0];
}
else
{
[myStoredEventsNew insertObject:tempDic atIndex:myStoredEvents.count];
}
NSLog(#"New dictonary before modification :%#",tempDic);
[prefs setObject:myStoredEventsNew forKey:#"MySavedEvents"];
[prefs synchronize];
Try this code --
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSLog(#"DEBUG :: %#",[prefs objectForKey:#"MySavedEvents"]);
NSMutableArray *myStoredEvents;
if ([prefs objectForKey:#"MySavedEvents"] == NULL) {
myStoredEvents = [[NSMutableArray alloc]init];
}else{
myStoredEvents=[[prefs objectForKey:#"MySavedEvents"] mutableCopy];
}
NSMutableArray *tempDic=[myevents objectAtIndex:eventId];//myevents a NSMutableArray
[myStoredEvents addObject:tempDic];
NSLog(#"New dictonary before modification :%#",myStoredEvents);
[prefs setObject:myStoredEvents forKey:#"MySavedEvents"];
[prefs synchronize];
May this solve your problem
you can save array in NSuserdefaults like this :-
[[NSUserDefaults standardUserDefaults] setObject:yourArray forKey:#"MySavedEvents"];
[[NSUserDefaults standardUserDefaults] synchronize];
and you can put check condition to check NSuserdefault like this :-
NSObject * object = [prefs objectForKey:#"MySavedEvents"];
if(object != nil){
//object is there
}
You can put further conditions according to your need, this is just a basic structure of how to achieve this.

Adding new values to existing keys of nsuserdefault using nsmutablearray

I am finding some problem while saving and retrieving data using nsuserdefaults.
What i want to do- iam accepting name and number from user from viewcontroller and saving it using nsuserdefault. when i click on save button i want to retrieve all the values from nsuserdefault and display it on tableview. now when i save the new data i want this data to get added to the existing data of nsuserdefault. can anyone help me with saving and retrieving nsuserdefault data.
----------MyCode---------------
nsuserdefaults *objdefault =[nsuserdefaults standarduserdefaults];
nameArray = [objdefault objectforkey:#"Name"];
[newNameArray addobject:txtName.text];
[nameArray addobject:newNameArray];
[objdefault setobject:nameArray forkey:#"Name"];
[objdefault synchronize];
all this saves and accepts null value
Please help. and thank you in advance
Use these methods to add name to NSUserDefaultsand get from NSUserDefaults
To add the name to NSUserDefaults call [self addNameToUserDefaults:#"abc"];
-(void)addNameToUserDefaults:(NSString *)name number:(NSString*)number{
NSUserDefaults *objdefault =[NSUserDefaults standardUserDefaults];
NSMutableArray *nameArray = [[objdefault objectForKey:#"NameAndNumber"] mutableCopy];
if(!nameArray)
nameArray = [#[] mutableCopy];
[nameArray addObject:#{#"name":name,#"number":number}];
[objdefault setObject:nameArray forKey:#"NameAndNumber"];
[objdefault synchronize];
}
To get all names from NSUserDefaults call NSMutableArray *names = [self getAllNames];
-(NSMutableArray *)getAllNames{
NSUserDefaults *objdefault =[NSUserDefaults standardUserDefaults];
return [[objdefault objectForKey:#"NameAndNumber"] mutableCopy];
}
It's not possible to add values for same in NSUSerDefaults. it will show you last value only. You should go for Core data or Sqlite. Still if you are not comfortable with that you can use plist to achieve this functionality.
This is what I have done in my project. You have to use NSMutableDictionary to add more value
- (void)addUserLocation:(NSString *)username location:(NSMutableDictionary *)location
{
NSString *currentUserKey = [NSString stringWithFormat:#"%#_%#", UserDefaultsKeyLocationData, username, nil];
NSMutableArray *oldData = [[NSMutableArray alloc]init];
if ([self loadUserLocation:username] != nil) {
oldData = [self loadUserLocation:username];
}
if (![oldData containsObject:location]) {
[oldData addObject:location];
}
[[NSUserDefaults standardUserDefaults] setObject:oldData forKey:currentUserKey];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSMutableDictionary *)loadUserLocation:(NSString *)username
{
NSString *currentUserKey = [NSString stringWithFormat:#"%#_%#", UserDefaultsKeyLocationData, username, nil];
return [[[NSUserDefaults standardUserDefaults] objectForKey:currentUserKey] mutableCopy];
}
If you want get all data. Please call loadUserLocation in your code

How to add objects into NSMutableArray without deleting the existing ones?

Im having trouble with my nsmutablearray in NSUserdefaults, this array every time I relaunch the app erases the objects that already are there and put the new ones, so I need help to prevent these to happen, Thanks and this is my code;
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
if (!self.tasks) self.tasks = [NSMutableArray new];
[self.tasks addObject:textField.text];
[userDefaults setObject:self.tasks forKey:#"tasks"];
//[userDefaults synchronize];
NSLog(#"tasks:%#", [[NSUserDefaults standardUserDefaults]objectForKey:#"tasks"]);
NSLog(#"number of tasks:%d", self.tasks.count);
And Im reading it in a tableview this way:
cell.taskTitle.text = (self.TasksArray)[indexPath.row];
Thanks!
You are missing a line of code there:
self.tasks = [[NSMutableArray alloc] initWithArray:[userDefaults objectForKey:#"tasks"];
As far as I can tell, you're not initially setting your ".tasks" property, so adding that bit may fix the problem.
You need to get it from user defaults first as rmaddy suggests. Your nil check will then create a new array if its never been created/saved before.
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
self.tasks = [[userDefaults objectForKey:#"tasks"] mutableCopy];
if (!self.tasks) self.tasks = [NSMutableArray new];
[self.tasks addObject:textField.text];
[userDefaults setObject:self.tasks forKey:#"tasks"];
//[userDefaults synchronize];
NSLog(#"tasks:%#", [[NSUserDefaults standardUserDefaults]objectForKey:#"tasks"]);
NSLog(#"number of tasks:%d", self.tasks.count);
I see you never call [[NSUserDefaults standardUserDefaults] synchronize];
Once you finish with changes of your object you should call it since it saves your changes to disk.

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.

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