我们如何存储到NSDictionary中? NSDictionary和NSMutableDictionary有什么区别?

时间:2009-11-19 01:34:13

标签: iphone objective-c nsdictionary nsmutabledictionary

我正在开发一个我想使用NSDictionary的应用程序。任何人都可以向我发送一个示例代码,解释如何使用NSDictionary存储数据的过程以及完美的示例吗?

3 个答案:

答案 0 :(得分: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”]

答案 1 :(得分: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];

答案 2 :(得分:18)

关键区别: NSMutableDictionary可以修改到位,NSDictionary不能。对于Cocoa中的所有其他NSMutable *类都是如此。 NSMutableDictionary是NSDictionary的子类,因此您可以使用NSDictionary执行所有操作。但是,NSMutableDictionary还添加了补充方法来修改现有的内容,例如方法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"];