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)
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)
这是你的期望.
| 归档时间: |
|
| 查看次数: |
51260 次 |
| 最近记录: |