如何在iphone中以编程方式创buildPLIST文件

我正在寻找创buildplist文件在我的应用程序的文件夹编程方式在客观C.我在文件目录中创build一个文件夹:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *path = [NSString stringWithFormat:@"%@/Data.plist", documentsDirectoryPath]; 

我正在尝试创build一个看起来像XML文件的plist文件。 / ****必需的XML文件**** /

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>height</key> <integer>4007</integer> <key>name</key> <string>map</string> <key>width</key> <integer>6008</integer> </dict> </array> </plist> 

/ ****通过代码实现文件**** /

 <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>height</key> <string>4007</string> <key>name</key> <string>map</string> <key>width</key> <string>6008</string> </dict> </plist> 

所需的文件需要一个数组,在数组内部有一个字典对象。 我怎样才能改变这个? 我也知道如何将文件写入path,但主要问题是如何创buildplist文件然后读取它?

PLIST文件(也称为“属性列表”文件)使用XML格式来存储对象,如数组,字典和string。

您可以使用此代码来创build,添加值并从plist文件中检索值。

 //Get the documents directory path NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:@"plist.plist"]; NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath: path]) { path = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat:@"plist.plist"] ]; } NSMutableDictionary *data; if ([fileManager fileExistsAtPath: path]) { data = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; } else { // If the file doesn't exist, create an empty dictionary data = [[NSMutableDictionary alloc] init]; } //To insert the data into the plist [data setObject:@"iPhone 6 Plus" forKey:@"value"]; [data writeToFile:path atomically:YES]; //To retrieve the data from the plist NSMutableDictionary *savedValue = [[NSMutableDictionary alloc] initWithContentsOfFile: path]; NSString *value = [savedValue objectForKey:@"value"]; NSLog(@"%@",value); 

我认为这个职位保存到.plist的本质列表将帮助你,如果你看看那里的例子。

此外,请查看苹果的创build属性列表编程文档的其他指导方针和示例。

请注意,如果您只想要一个plist文件来保存数据,则不必真正创build并保存任何数据。 有一种叫做NSUserDefaults的机制。 你做类似的事情

 [[NSUserDefaults standardUserDefaults] setInteger:1234 forKey:@"foo"]; 

和你一样阅读

 NSInteger foo=[[NSUserDefaults standardUserDefaults] integerForKey:@"foo"]; // now foo is 1234 

准备文件保存,写入文件,下次启动应用程序时再次阅读, 自动完成!

阅读正式的参考和官方文件 。