我们如何可以存储到一个NSDictionary? NSDictionary和NSMutableDictionary有什么区别?

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

NSDictionary和NSMutableDictionary文档可能是你最好的select。 他们甚至还有一些关于如何做各种事情的很好的例子,比如…

…创build一个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年开始,你可以inputdict [@“key”]而不是[dict objectForKey:@“key”]

 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]; 

关键的区别: 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"];