Saving NSDictionary to NSUserDefaults
Solution 1:
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];
Solution 2:
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.