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];
Related
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];
language: Objective-C,
I'm new at iOS development so please guide me in a easiest way if you can, i'm saving data into dictionary then NSUserDefaults after that i want to get the data from they NSUserDefaults, I'm working when user clicked in a texfield then text should be stored into dictionary but when i check into Xcode after setting a break points dictionary shows nil. I'm sending screenshots and code please help me.
Thanks
initialization of dictionary in viewDidLoad
save to NSUserDefaults
-(void)textFieldDidEndEditing:(UITextField *)textField {
//we'll use the following method if the TF is out of the table means not in a cell.
if([textField isEqual:self.getNameLabel]){
[nameDateDict setObject:[textField text] forKey:K_NAME];
[self saveToNSUserDefaults];
}
}
Xcode-output
nameDateDict NSMutableDictionary * nil 0x0000000000000000
Sorry the name of texfield is getNameLabel, I'll edit it later so please don't confuse after reading the name.
Even that i've checked this code is working
[timeDict setObject:#"Hello" forKey:#"Greetings"];
[timeDict setObject:#"Bye" forKey:#"B_Key"];
[timeDict setObject:#"what?" forKey:#"W_Key"];
[[NSUserDefaults standardUserDefaults] setObject:timeDict forKey:#"Greetings"];
[[NSUserDefaults standardUserDefaults] setObject:timeDict forKey:#"B_Key"];
[[NSUserDefaults standardUserDefaults] setObject:timeDict forKey:#"W_Key"];
[[NSUserDefaults standardUserDefaults] synchronize];
timeDict = [[NSUserDefaults standardUserDefaults] objectForKey:#"Greetings"];
timeDict = [[NSUserDefaults standardUserDefaults] objectForKey:#"B_Key"];
timeDict = [[NSUserDefaults standardUserDefaults] objectForKey:#"W_Key"];
A couple of things are going on here. First, you have a scope problem, in that your create a local dictionary object in viewDidLoad, which you can't access later. It looks as though you'll want to have an NSMutableDictionary property available for the class, which should be designated either in the header file or interface extension in the implementation file (depending on your use of this dictionary in your project):
#property (nonatomic, strong) NSMutableDictionary *nameDateDictionary;
Second, you aren't correctly initializing or accessing your dictionary and it's objects. So, (using some literal syntax shortcuts) your viewDidLoad and saveToNSUserDefaults methods:
- (void)viewDidLoad
{
[super viewDidLoad];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *name = [defaults objectForKey:K_NAME];
NSDate *startDate = [defaults objectForKey:K_START_DATE];
NSDate *endDate = [defaults objectForKey:K_END_DATE];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:#{K_NAME: name,
K_START_DATE: startDate,
K_END_DATE: endDate}];
self.nameDateDictionary = dict;
}
- (void)saveToNSUserDefaults
{
NSMutableDictionary *dict = self.nameDateDictionary;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:dict[K_NAME] forKey:K_NAME];
[defaults setObject:dict[K_START_DATE] forKey:K_START_DATE];
[defaults setObject:dict[K_END_DATE] forKey:K_END_DATE];
[defaults synchronize];
}
- (BOOL)textFieldShouldReturn:(UITextField*)theTextField {
[theTextField resignFirstResponder];
return YES;
}
-(void) textFieldDidEndEditing:(UITextField *)textField {
[self saveToNSUserDefaults:#{#"keyName":textField.text}];
}
-(void)saveToNSUserDefaults:(NSDictionary *)dict{
[[NSUserDefaults standardUserDefaults] setObject:dict forKey:#"myDictionary"];
}
-(void *)retrieveFromNSUserDefaults{
NSDictionary *tempDict=[[NSDictionary alloc] initWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:#"myDictionary"]];
NSlog(#"TextField Value: %#",[tempDict objectForKey:#"keyName"]);
}
The way you are storing the dictionary was not correct. Please go through the https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSDictionary_Class/index.html for more about how to use them.
Everyone came from a beginner's stage but try not to skip the basics.
As on your screenshots you are storing dictionary values in a wrong way, you store each time the whole dictionary to each NSUserDefaults key. It schoul be like that:
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:#"value" forKey:#"key"];
[[NSUserDefaults standardUserDefaults] setObject:[dict objectForKey:#"key"] forKey:#"key"];
To get back a value from NSUserDefaults to dictionary:
[dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:#"key"] forKey:#"key"];
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 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
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.