lif*_*son 15 iphone cocoa-touch objective-c plist ios
我想在目标C中以编程方式在我的应用程序Documents文件夹中创建plist文件.我在文档目录中创建一个文件夹:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *path = [NSString stringWithFormat:@"%@/Data.plist", documentsDirectoryPath];
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个看起来像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>
Run Code Online (Sandbox Code Playgroud)
/****通过代码****/获得文件
<?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>
Run Code Online (Sandbox Code Playgroud)
所需文件需要一个数组,在数组中我们有一个字典对象.我怎么能改变这个?我也知道如何将文件写入路径,但主要问题是如何创建plist文件然后读取它?
Ara*_*han 67
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
36159 次 |
| 最近记录: |