将NSDictionary保存到NSUserDefaults

将NSDictionary保存到NSUserDefaults

本文介绍了将NSDictionary保存到NSUserDefaults的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

1。)我的代码如下;我不知道如果它是正确的,我还需要知道如何从NSUSerDefault检索NSMutableDictionary?

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 ?

2。)检索NSMutableDictionary后,我需要保存它到一个NSDictionary。我如何做这些?

2.) After retrieving the NSMutableDictionary i need to save it to a NSDictionary. How could i do these ?

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 不区分可变对象和不可变对象,所以当你得到它时,它将是不可变的:

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"];

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

If you want a mutable dictionary, just use mutableCopy:

NSMutableDictionary *mutableRetrievedDictionary = [[[NSUserDefaults standardUserDefaults] objectForKey:@"DicKey"] mutableCopy];

这篇关于将NSDictionary保存到NSUserDefaults的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:38