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

标签 iphone objective-c ios cocoa-touch plist

我想在 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/

相关文章:

ios - 如何将 Touch ID 与登录凭据相关联?

objective-c - 启动时在 iPhone Objective-C 项目中执行 C 代码

iphone - 以编程方式在 CircleImage 上创建 UIButton

iphone - 在耳机中播放 iPhone 音频

iphone - iOS 上 Safari 中的 HTML 5/QuickTime 音频缓存

ios - 为什么要为即将推出的 iPhone 6 的大屏幕使用 Storyboard?不同之处?

ios - 如何访问已激活 plist 的程序集?

ios - NSURLSessionConfiguration TLSMinimumSupportedProtocol 看起来在 iOS 上不起作用

iphone - 分析器报告以下代码泄漏

ios - UIView 没有接收到触摸事件,但它下面的 View 是