Priya Priya - 2 years ago 94
Objective-C Question

How to Store multiple disctionary in NsUserDefault

I have two Viewcontrollers in FirstVC i build 5

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

below is code of my FirstVC


//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];
ArratTemp = [[[NSUserDefaults standardUserDefaults]objectForKey:@"ABC"]mutableCopy];

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download