将NSDictionary保存到NSUserDefaults

我有一个NSMutableDictionary,我已经添加了值(几个关键对值)。 现在我需要将此NSMutableDictionary保存到一个NSUserDefaults对象。

1.)我的代码如下; 我不知道这是否是正确的,我也需要知道如何从NSUSerDefault检索NSMutableDictionary?

2)检索NSMutableDictionary后,我需要将其保存到一个NSDictionary。 我怎么能做到这些?

NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; [dic addObject:@"sss" forKey:@"hi"]; [dic addObject:@"eee" forKey:@"hr"]; [NSUserDefaults standardDefaults] setObject:dic forKey:@"DicKey"]; [[NSUserDefaults standardDefaults] synchronize]; 

你的代码是正确的,但你必须记住的一件事是, NSUserDefaults不区分mutable和immutable对象,所以当你得到它时,它将是不可变的:

 NSDictionary *retrievedDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"DicKey"]; 

如果你想要一个可变的字典,只需使用mutableCopy

 NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy]; 
 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]; 

这是你所期望的。