iOS 对plist文件进行读写,增删改查的实例
程序员文章站
2023-12-16 15:05:04
对plist文件进行读写
//获取路径对象
nsarray *patharray = nssearchpathfordirectoriesindomain...
对plist文件进行读写
//获取路径对象 nsarray *patharray = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *path = [patharray objectatindex:0]; //获取文件的完整路径 nsstring *filepatch = [path stringbyappendingpathcomponent:@"column.plist"]; nslog(@"%@",filepatch); //写入数据到plist文件 nsmutabledictionary *dic1 = [nsmutabledictionary dictionarywithobjectsandkeys:@"小小虎",@"name",@"5",@"age",@"boy",@"sex",nil]; nsmutabledictionary *dic2 = [nsmutabledictionary dictionarywithobjectsandkeys:@"小小兮",@"name",@"6",@"age",@"girl",@"sex",nil]; //将上面2个小字典保存到大字典里面 nsmutabledictionary *datadic = [nsmutabledictionary dictionary]; [datadic setobject:dic1 forkey:@"一年级"]; [datadic setobject:dic2 forkey:@"二年级"]; //写入plist里面 [datadic writetofile:filepatch atomically:yes]; //读取plist文件的内容 nsmutabledictionary *datadictionary = [[nsmutabledictionary alloc] initwithcontentsoffile:filepatch]; nslog(@"---plist一开始保存时候的内容---%@",datadictionary);
对pilst文件进行修改
//修改字典里面的内容,先按照结构取到你想修改内容的小字典 nsmutabledictionary *dd = [datadictionary objectforkey:@"一年级"]; [dd setobject:@"我改名字了哦" forkey:@"name"]; [dd setobject:@"我添加的新内容" forkey:@"content"]; [dd removeobjectforkey:@"age"]; //修改成功以后,将这个小字典重新添加到大字典里面 [datadictionary setobject:dd forkey:@"一年级"]; [datadictionary writetofile:filepatch atomically:yes]; nslog(@"---plist做过操作之后的字典里面内容---%@",datadictionary);
删除
//清除plist文件,可以根据我上面讲的方式进去本地查看plist文件是否被清除 nsfilemanager *filemger = [nsfilemanager defaultmanager]; nsstring *xiaoxipath = [[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes)objectatindex:0]stringbyappendingpathcomponent:@"xiaoxi.plist"]; //如果文件路径存在的话 bool bret = [filemger fileexistsatpath:xiaoxipath]; if (bret) { nserror *err; [filemger removeitematpath:xiaoxipath error:&err]; }
以上这篇ios 对plist文件进行读写,增删改查的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。