将NSDictionary保存到NSUserDefaults

编程入门 行业动态 更新时间:2024-10-28 11:29:43
本文介绍了将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

本文发布于:2023-07-16 14:39:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1122705.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSDictionary   NSUserDefaults

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!