将NSDictionary保存到NSUserDefaults

sha*_*jem 47 iphone cocoa-touch objective-c ios

我有一个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];
Run Code Online (Sandbox Code Playgroud)

yuj*_*uji 84

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

NSDictionary *retrievedDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"DicKey"];
Run Code Online (Sandbox Code Playgroud)

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

NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy];
Run Code Online (Sandbox Code Playgroud)

  • 无论如何,手动管理记忆就像. (23认同)
  • 我正在使用ARC.而且,我需要将NSMutableDictionary保存到NSUser Defaults,并从NSUserDefaults获取NSDictionary.所以我必须使用你的第一种方法? (2认同)
  • 哎呀,需要做`mutableCopy`而不是`copy`来得到一个可变的字典.但是,对于你描述的内容,你需要第一个版本. (2认同)

KkM*_*MIW 6

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];
Run Code Online (Sandbox Code Playgroud)

这是你的期望.