Priya Priya - 6 months ago 36
iOS Question

How to Store multiple dictionary in NSUserDefaults

I have two Viewcontrollers in FirstVC i build 5

UITextField
for registration ,this TextField value are stroed in dictionary finally the dictionary stored in
NSUserdefault
then in SecondVC i want to show this data
My problem is that each time when i add new discretionary in
NSUserdefault
The old one dictionary was replaced
i want data of all dictionary.

below is code of my FirstVC

-(void)btnReg

{
//data add in disctionary
for (int i=1; i<=5; i++)
{
UITextField *txtTemp=(UITextField *)[self.view viewWithTag:i];
[discRege setObject:[NSNumber numberWithInt:count] forKey:@"no"];
[discRege setObject:txtTemp.text forKey:[arraylblName objectAtIndex:i-1]];
}
//dictionary add in nsuserdefault

[[NSUserDefaults standardUserDefaults]setObject:discRege forKey:@"ABC"];
[[NSUserDefaults standardUserDefaults]synchronize];

//push to SecondVc
secondViewController *objSec=[[secondViewController alloc]init];
[self.navigationController pushViewController:objSec animated:YES];
[self.navigationController setNavigationBarHidden:false];

}


below is code of my SecondVC

ArratTemp =[[NSUserDefaults standardUserDefaults]objectForKey:@"ABC"] ;
if (!ArratTemp )
{
ArratTemp =[[NSMutableArray alloc]init];
}
else
{
ArratTemp = [[[NSUserDefaults standardUserDefaults]objectForKey:@"ABC"]mutableCopy];
}
NSLog(@"%@",ArratTemp);

Answer

Every time you are using the same key and replacing the existing dictionary object...

// Using the same key will overwrite the last saved dictionary.
[[NSUserDefaults standardUserDefaults]setObject:discRege forKey:@"ABC"];

Instead of storing it as dictionary, store as array of dictionary, whenever you add new registration, fetch the saved array, add new dictionary object into it and update the userDefaults with that array.

mutableArray = [[[NSUserDefaults standardUserDefaults]objectForKey:@"ABC"]mutableCopy];
[mutableArray addObject: discReg]
[[NSUserDefaults standardUserDefaults]setObject:mutableArraay forKey:@"ABC"];
[[NSUserDefaults standardUserDefaults]synchronize];

Hope it helps.

Comments