xcode 如何创建和使用我自己的 .plist 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13709286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create and use my own .plist file
提问by jkally
I have to create a .plist file manually in Xcode, then add to it some constant data (kind of a small database), several objects, each having a string and a number. Then read it in my program into an array every time the program starts. The .plist file doesn't change. I cannot find a way to create a .plist and fill it with data manually.
我必须在 Xcode 中手动创建一个 .plist 文件,然后向其中添加一些常量数据(一种小型数据库),几个对象,每个对象都有一个字符串和一个数字。然后每次程序启动时将它在我的程序中读入数组。.plist 文件不会改变。我找不到创建 .plist 并手动填充数据的方法。
回答by Majster
Well its quite easy. Since you wont be altering it you can add it as file->new->resource->plist.. Then manually enter the data the way you like.
那么它很容易。由于您不会更改它,您可以将其添加为 file->new->resource->plist.. 然后按照您喜欢的方式手动输入数据。
Reading plists can be done like so:
阅读 plist 可以这样完成:
NSURL *file = [[NSBundle mainBundle] URLForResource:@"myplist" withExtension:@"plist"]; //Lets get the file location
NSDictionary *plistContent = [NSDictionary dictionaryWithContentsOfURL:file];
And accessing to things in the plist would be like:
访问 plist 中的内容将如下所示:
NSString *playerName = [plistContent objectForKey@"player"];
Set the key name in the xcode plist editor. Note that this only works for reading. For writing to a plist you must copy it over to the documents directory of the applicaion. I can post that for you as well if you need it.
在 xcode plist 编辑器中设置键名。请注意,这仅适用于阅读。要写入 plist,您必须将其复制到应用程序的文档目录中。如果您需要,我也可以为您发布。
回答by Daij-Djan
you use a NSMutableDictionary, give it a NSMutableArray as a child and then call writeToFile
你使用 NSMutableDictionary,给它一个 NSMutableArray 作为孩子,然后调用 writeToFile
working sample code:
工作示例代码:
NSMutableArray *myArrayToWrite = [NSMutableArray array];
[myArrayToWrite addObject:@"blablub"];
[myArrayToWrite addObject:[NSNumber numberWithInt:123]];
NSMutableDictionary *plistToWrite = [NSMutableDictionary dictionary];
[plistToWrite setObject:myArrayToWrite forKey:@"data"];
[plistToWrite writeToFile:@"/Users/Shared/TEMP.plist" atomically:NO];
//---
NSDictionary *plistRead = [NSDictionary dictionaryWithContentsOfFile:@"/Users/Shared/TEMP.plist"];
NSArray *arrayRead = [plistRead objectForKey:@"data"];
NSLog(@"%@", arrayRead);