大家好,我是你的好朋友思创斯。今天说一说ios学习之 plist文件的读写,希望您对编程的造诣更进一步.
在做ios开发时,经常用到到plist文件, 那plist文件是什么呢? 它全名是:property list,属性列表文件,它是一种用来存储串行化后的对象的文件。属性列表文件的扩展名为.plist ,因此通常被称为 plist文件。文件是xml格式的。
plist文件通常用于储存用户设置,也可以用于存储捆绑的信息
我们创建一个项目来学习plist文件的读写。
1、创建项目plistdemo
项目创建之后可以找到项目对应的plist文件,打开如下图所示:
在编辑器中显示类似与表格的形式,可以在plist上右键,用源码方式打开,就能看到plist文件的xml格式了。
2、创建plist文件。
按command n快捷键创建,或者file —> new —> new file,选择mac os x下的property list
创建plist文件名为plistdemo。
打开plistdemo文件,在空白出右键,右键选择add row 添加数据,添加成功一条数据后,在这条数据上右键看到 value type选择dictionary。点加号添加这个dictionary下的数据
添加完key之后在后面添加value的值,添加手机号和年龄
创建完成之后用source code查看到plist文件是这样的:
jack
phone_num
13801111111
age
22
tom
phone_num
13901111111
age
36
是否还在为ide开发工具频繁失效而烦恼,来吧关注以下公众号获取最新激活方式。亲测可用!
【正版授权,激活自己账号】:
【官方授权 正版激活】:
3、读取plist文件的数据
- (void)viewdidload
{
[super viewdidload];
//读取plist
nsstring *plistpath = [[nsbundle mainbundle] pathforresource:@"plistdemo" oftype:@"plist"];
nsmutabledictionary *data = [[nsmutabledictionary alloc] initwithcontentsoffile:plistpath];
nslog(@"%@", data);//直接打印数据。
}
plistdemo[6822:f803] {
jack = {
age = 22;
"phone_num" = 13801111111;
};
tom = {
age = 36;
"phone_num" = 13901111111;
};
}
这样就把数据读取出来了。
4、创建和写入plist文件
在开发过程中,有时候需要把程序的一些配置保存下来,或者游戏数据等等。 这时候需要写入plist数据。
写入的plist文件会生成在对应程序的沙盒目录里。
接着上面读取plist数据的代码,加入了写入数据的代码,
- (void)viewdidload { [super viewdidload]; //读取plist nsstring *plistpath = [[nsbundle mainbundle] pathforresource:@"plistdemo" oftype:@"plist"]; nsmutabledictionary *data = [[nsmutabledictionary alloc] initwithcontentsoffile:plistpath]; nslog(@"%@", data); //添加一项内容 [data setobject:@"add some content" forkey:@"c_key"]; //获取应用程序沙盒的documents目录 nsarray *paths=nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask,yes); nsstring *plistpath1 = [paths objectatindex:0]; //得到完整的文件名 nsstring *filename=[plistpath1 stringbyappendingpathcomponent:@"test.plist"]; //输入写入 [data writetofile:filename atomically:yes]; //那怎么证明我的数据写入了呢?读出来看看 nsmutabledictionary *data1 = [[nsmutabledictionary alloc] initwithcontentsoffile:filename]; nslog(@"%@", data1); // do any additional setup after loading the view, typically from a nib. }
在获取到自己手工创建的plistdemo.plist数据后,在这些数据后面加了一项内容,证明输入写入了。
怎么证明添加的内容写入了呢?下面是打印结果:
代码地址:https://github.com/schelling/ycdemo/tree/master/plistdemo
著作权声明:本文由原创,欢迎转载分享。请尊重作者劳动,转载时保留该声明和作者博客链接,谢谢!
文章由思创斯整理,转载请注明出处:https://ispacesoft.com/129644.html