我们如何存储到 NSDictionary 中? NSDictionary 和 NSMutableDictionary 有什么区别?
我正在开发一个应用程序,我想在其中使用 NSDictionary
。谁能给我发送一个示例代码,解释如何使用 NSDictionary 来存储数据的完美示例?
I am developing an application in which I want to use an NSDictionary
. Can anyone please send me a sample code explaining the procedure how to use an NSDictionary
to store Data with a perfect example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSDictionary 和NSMutableDictionary 文档可能是您最好的选择。他们甚至有一些关于如何做各种事情的很好的例子,比如...
...创建一个 NSDictionary
...迭代它
...make它是可变的
注意:2010 年之前的历史版本:[[dictionary mutableCopy] autorelease]
...并更改它
...然后将其存储到一个文件
...然后再次读取它
...读取一个值
...检查密钥是否存在
<强>...使用可怕的未来语法
从 2014 年开始,你实际上可以只输入 dict[@"key"] 而不是 [dict objectForKey:@"key"]
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
...iterate over it
...make it mutable
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
...then store it to a file
...and read it back again
...read a value
...check if a key exists
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
主要区别:NSMutableDictionary 可以就地修改,NSDictionary 不能。对于 Cocoa 中的所有其他 NSMutable* 类来说都是如此。 NSMutableDictionary 是 NSDictionary 的子类,因此您可以使用 NSDictionary 执行的所有操作都可以使用两者执行。不过,NSMutableDictionary 还添加了补充方法来就地修改内容,例如方法
setObject:forKey:
。您可以像这样在两者之间进行转换:
假设您希望通过将数据写入文件来存储数据。 NSDictionary 有一个方法可以做到这一点(也适用于 NSMutableDictionary):
要从文件中读取字典,有一个相应的方法:
如果您想将文件作为 NSMutableDictionary 读取,只需使用:
The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method
setObject:forKey:
.You can convert between the two like this:
Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):
To read a dictionary from a file, there's a corresponding method:
If you want to read the file as an NSMutableDictionary, simply use: