我们如何存储到NSDictionary中? NSDictionary和NSMutableDictionary有什么区别? [英] How can we store into an NSDictionary? What is the difference between NSDictionary and 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?
推荐答案
NSDictionary 和 NSMutableDictionary 文档可能是你最好的选择。他们甚至有一些关于如何做各种事情的很好的例子,比如......
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...创建一个NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...迭代它
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...让它变得可变
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
注意:2010年之前的历史版本:[[dictionary mutableCopy] autorelease]
...并改变它
[mutableDict setObject:@"value3" forKey:@"key3"];
...然后将其存储到文件中
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...并再次阅读
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...读取值
NSString *x = [anotherDict objectForKey:@"key1"];
...检查密钥是否存在
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...使用可怕的未来语法
从2014年开始你可以输入dict [@key]而不是[dict objectForKey:@key]
这篇关于我们如何存储到NSDictionary中? NSDictionary和NSMutableDictionary有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!