ios 将 NSDictionary 保存到 NSUserDefaults
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9947073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Saving NSDictionary to NSUserDefaults
提问by shajem
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.
我有一个 NSMutableDictionary,我已经向它添加了值(几个键对值)。现在我需要将此 NSMutableDictionary 保存到 NSUserDefaults 对象。
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 ?
1.) 我的代码如下;我不确定它是否正确,而且我还需要知道如何从 NSUSerDefault 检索 NSMutableDictionary ?
2.) After retrieving the NSMutableDictionary i need to save it to a NSDictionary. How could i do these ?
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];
回答by yuji
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:
您的代码是正确的,但您必须记住的一件事是NSUserDefaults
不区分可变对象和不可变对象,因此当您取回它时,它将是不可变的:
NSDictionary *retrievedDictionary = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"DicKey"];
If you want a mutable dictionary, just use mutableCopy
:
如果你想要一个可变的字典,只需使用mutableCopy
:
NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy];
回答by KkMIW
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.
这是你所期望的。