gpt4 book ai didi

iphone - 如何在 iphone 中以编程方式创建 PLIST 文件

转载 作者:IT王子 更新时间:2023-10-29 08:21:21 24 4
gpt4 key购买 nike

我想在 Objective-C 中以编程方式在我的应用程序文档文件夹中创建 plist 文件。我在文档目录中创建了一个文件夹:

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

我正在尝试创建看起来像 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>

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

最佳答案

PLIST 文件,也称为“属性列表”文件,使用 XML 格式存储对象,例如数组、字典和字符串。

您可以使用此代码创建、添加值以及从 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);

关于iphone - 如何在 iphone 中以编程方式创建 PLIST 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6697247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com