68

我正在开发一个应用程序,我想在其中使用NSDictionary. 谁能给我一个示例代码,解释如何使用NSDictionary一个完美的例子来存储数据的过程?

4

3 回答 3

191

NSDictionaryNSMutableDictionary文档可能是你最好的选择。他们甚至有一些关于如何做各种事情的很好的例子,比如......

...创建一个 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"]

于 2009-11-19T01:40:31.073 回答
32
NSDictionary   *dict = [NSDictionary dictionaryWithObject: @"String" forKey: @"Test"];
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionary];

[anotherDict setObject: dict forKey: "sub-dictionary-key"];
[anotherDict setObject: @"Another String" forKey: @"another test"];

NSLog(@"Dictionary: %@, Mutable Dictionary: %@", dict, anotherDict);

// now we can save these to a file
NSString   *savePath = [@"~/Documents/Saved.data" stringByExpandingTildeInPath];
[anotherDict writeToFile: savePath atomically: YES];

//and restore them
NSMutableDictionary  *restored = [NSDictionary dictionaryWithContentsOfFile: savePath];
于 2009-11-19T01:39:54.810 回答
18

关键区别:NSMutableDictionary 可以就地修改, NSDictionary 不能。这适用于 Cocoa 中的所有其他 NSMutable* 类。NSMutableDictionary 是 NSDictionary 的子类,所以你可以用 NSDictionary 做的所有事情你都可以做。但是,NSMutableDictionary 还添加了补充方法来修改就地的东西,例如 method setObject:forKey:

您可以像这样在两者之间进行转换:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

大概您想通过将数据写入文件来存储数据。NSDictionary 有一个方法可以做到这一点(也适用于 NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

要从文件中读取字典,有一个相应的方法:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

如果您想将文件作为 NSMutableDictionary 读取,只需使用:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];
于 2009-11-19T01:41:07.587 回答