1. 手动创建.plist文件
使用Xcode打开你的项目,使用快捷键 command + n 键 打开Xcode的模版框,找到Property List
![](https://img.haomeiwen.com/i4652656/4b0e77abdb5a34a6.png)
点击Next 按钮
![](https://img.haomeiwen.com/i4652656/c0fcae7a7aa8f374.png)
图中红色的框填入你要创建的plist文件名字
黄色框是plist文件保存的项目Finder的文件夹
绿色框是plist文件在Xcode中左侧绿框看到文件夹
注意:名字不可以使用"Info" 否则会跟项目中的Info.plist产生冲突
点击Create创建
![](https://img.haomeiwen.com/i4652656/863bfdc12760d689.png)
这个就是我们创建的plist文件
注意:只能读取,代码不能增删改,在bundle文件中的plist文件是无法修改的,如果更改需要先从Bundle中移出才可以,把Plist文件从bundle复制到cache目录下,然后数据就可以改变了
读取plist文件代码
//获取文件路径
NSString *path = [[NSBundle mainBundle] pathForResource:@"CreatePlistList" ofType:@"plist"];
NSMutableDictionary *userDictionary = [NSMutableDictionary dictionaryWithContentsOfFile:path];
NSString *name = userDictionary[@"XXX"];
NSString *age = userDictionary[@"XXX"];
NSLog(@"name:%@ \n age:%@",name,age);
2. 代码创建
NSDictionary *userDictionary = @{@"name":@"花花",
@"age":@"18"
};
///获取本地沙盒Document路径
NSArray *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [documentPath objectAtIndex:0];
///在Document路径下拼接文件名字
NSString *plistPath = [path stringByAppendingPathComponent:@"CodeCreatePlistList.plist"];
NSFileManager *fileManager = [NSFileManager defaultManager];
///检测plistPath路径是否存在
BOOL isFile = [fileManager fileExistsAtPath:plistPath];
if (isFile) {
///文件存在 删除之后 写入
[fileManager removeItemAtPath:plistPath error:nil];
}
///plist文件写入
BOOL isSuccess = [userDictionary writeToFile:plistPath atomically:YES];
NSLog(@"写入成功 %@",@(isSuccess));
你可以在拼接文件路径的时候打印文件路径,去finder文件查看,找到创建的文件。
代码demo GitHub链接 https://github.com/ShawnWang1/CreatePlistDemo.git
网友评论