繁体   English   中英

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

[英]How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

我正在开发一个要使用NSDictionary的应用程序。 任何人都可以给我发送示例代码来说明如何使用NSDictionary存储数据的过程的一个完美示例吗?

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]自动发行]

...并更改它

[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   *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不能 可可中的所有其他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"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM