Saving a list of indexPaths - ios

I normally save the selected indexPath of a UiTableView in NSUserDefaults, this is how I normally do it:
self.lastIndexPathUsed = indexPath.row;
NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
[userdefaults setObject:[NSString stringWithFormat:#"%ld",(long)indexPath.row] forKey:#"lastIndexPathUsedForSellerType"];
[[NSUserDefaults standardUserDefaults] synchronize];
Then I restore it:
self.lastIndexPathUsed = [[[NSUserDefaults standardUserDefaults] objectForKey:#"lastIndexPathUsedForSellerType"] floatValue];
So self.lastIndexPathUsed is just a float value.
The above works fine on a single select table view. However on a multi-select tableview I can't see to get it working.
While the UITableView is on screen I save all the indexPaths into an array. However saving that array into NSUserDefaults causes a crash due to indexPath not being an object as such.
How to save an array how indexPaths into NSUserDefaults?

Try to archive your array to NSData before saving them to NSUserDefaults:
NSData *indexPathArrayData = [NSKeyedArchiver archivedDataWithRootObject:_indexPathArray];
and after getting the NSData from NSUserDefaults, you can unarchive them :
_indexPathArray = [NSKeyedUnarchiver unarchiveObjectWithData:indexPathArrayData];

You can try this :
[[NSUserDefaults standardUserDefaults] setObject:yourMutableArray forKey:#"Key"];
And then get it like this :
NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"Key"]];
Hope it helps.

Related

how to remove an object inside an NSMutableDictionary which is inside a NSUserDefaults

I am trying to remove an object from a dictionary which is in userdefaults.
NSMutableDictionary *userDefaults = (NSMutableDictionary*)[[NSUserDefaults standardUserDefaults] dictionaryRepresentation];
[userDefaults removeObjectForKey:#"XYZ"];
The above code removes the whole dictionary.
XYZ is a NSMutuableDictionary. I want to remove an object with key "Password" from XYZ.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *dict = [[defaults objectForKey:#"XYZ"] mutableCopy];
[dict removeObjectForKey:#"Password"];
[defaults setObject:dict forKey:#"XYZ"];
This should do it:
// Access the dictionary you want to edit as a mutable copy
NSMutableDictionary *dict = [[[NSUserDefaults standardUserDefaults] objectForKey:#"dictKey"] mutableCopy];
// Remove the object for the key
[dict removeObjectForKey:#"keyToRemove"];
// Set the dictionary back in user defaults
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"dictKey"];
// Save your changes:
// If you need
// In applicationDidEnterBackground: in iOS >= 7.0
// If you are using iOS < 7.0
[[NSUserDefaults standardUserDefaults] synchronize];

Removing nsdata stored in nsuserdefault

I am saving image data (NSData) as an Array in NSUserDefault,while relaunching the app and try to remove the imagedata from the array stored in NSUserDefault,the data is not removing ..
Suppose you have store image data with key 'imagedata' something like below line of code
[[NSUserDefaults standardUserDefaults] setObject:imageData forKey :#"imageData"];
How to remove data stored for key imageData is as below line of code:
NSMutableArray *arr= [[NSUserDefaults standardUserDefaults] objectForKey:#"imageData"]]mutableCopy];// If array is not mutable then make it mutable then remove
[arr removeObjectAtIndex:index];
[[NSUserDefaults standardUserDefaults] setObject:arr forKey :#"imageData"];
After checking your code updating my answer
UPDATE
Try method removeObjectIdenticalTo of array.
//sample data
NSArray *photos = [NSArray arrayWithObjects:#"photo1.png",#"photo2.png",#"photo2.png", nil];
//To save the array of data
NSUserDefaults *userPreferences = [NSUserDefaults standardUserDefaults];
[userPreferences setObject:photos forKey:#"FbPhoto"];
[userPreferences synchronize];
//To remove
[userPreferences removeObjectForKey:#"FbPhoto"];
[userPreferences synchronize];

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.

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.

NSMutableArray adding elements get overwritten in iPhone

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];

Resources