Reputation: 2121
I have a NSMutableDictionary, and i have added values to it (several key pair values). Now i require to save this NSMutableDictionary to a NSUserDefaults object.
1.) My code as follows; I am not sure if it is correct , and also i need to know how to retrieve the NSMutableDictionary from the NSUSerDefault ?
2.) After retrieving the NSMutableDictionary i need to save it to a NSDictionary. How could i do these ?
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic addObject:@"sss" forKey:@"hi"];
[dic addObject:@"eee" forKey:@"hr"];
[NSUserDefaults standardDefaults] setObject:dic forKey:@"DicKey"];
[[NSUserDefaults standardDefaults] synchronize];
Upvotes: 50
Views: 54445
Reputation: 1112
NSMutableDictionary *profileDictionary = [[NSMutableDictionary alloc] init];
[profileDictionary setObject:txt_Username.text forKey:@"USERNAME_KEY"];
[profileDictionary setObject:txt_Password forKey:@"PASSWORD_KEY"];
[[NSUserDefaults standardUserDefaults] setObject:profileDictionary forKey:@"PROFILE_KEY"];
[[NSUserDefaults standardUserDefaults] synchronize];
This is what you expected.
Upvotes: 7
Reputation: 16725
Your code is correct, but the one thing you have to keep in mind is that NSUserDefaults
doesn't distinguish between mutable and immutable objects, so when you get it back it'll be immutable:
NSDictionary *retrievedDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"DicKey"];
If you want a mutable dictionary, just use mutableCopy
:
NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy];
Upvotes: 88