pist 最为持久化保存的一种方式!本身plist文件是xml ,对于小数量数据可以采用plis 的方法!这样更高效!废话不多说了!进入正题吧!如果是一个新手用plist的话一定会遇到各种问题!我当时就是这样走过来的!也是做个总结吧!
功能介绍:保存学生的基本信息:
一.
在故事板上拖拽几个控件吧如下图用来输入学生的信息
并在viewcontroller.h 里关联相应的控件!
@interface viewcontroller : uiviewcontroller
@property (weak, nonatomic) iboutlet uitextfield *studentnumbertextfield;
@property (weak, nonatomic) iboutlet uitextfield *studentnametextfield;
@property (weak, nonatomic) iboutlet uitextfield *studentnationtextfield;
@property (weak, nonatomic)iboutletuitextfield *studentagetextfield;
二.创建一个保存学生信息的类 savestudentmessageplist 并继承 nsobject
savestudentmessageplist.h 文件里创建一个初始化的函数
#import <foundation/foundation.h>
@interface savestudentmessageplist : nsobject
-(id)initwithstudentname:(nsstring *)name studentage:(nsstring *)age studentnumber:(nsstring * )numerb studentnation:(nsstring *)nation;
@end
//////////////////////////////////////////在.m文件里实现方法///////////////////////////////////////////////////////////////////
-(id)initwithstudentname:(nsstring *)name studentage:(nsstring *)age studentnumber:(nsstring * )numerb studentnation:(nsstring *)nation
{
//我们把学生的信息保存在可变数组里
nsmutablearray *studentmessagearray = [[nsmutablearray alloc]initwithobjects:name,age,numerb,nation,nil];
if (self = [superinit])
{
[self createstudentmessageplist:studentmessagearraykey:numerb]; // 因为学生的学号是唯一的作为词典的key值
}
return self;
}
// 创建plist 写入操作
-(void)createstudentmessageplist:(nsmutablearray *)studentmessagearray key:(nsstring *)studentnumebr
//沙盒路径
nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask,yes);
nsstring *documentsdirectory = [paths objectatindex:0];
// plist 路径
nsstring *plistpath = [documentsdirectorystringbyappendingpathcomponent:@"student.plist"];
nsfilemanager *filemanager = [[nsfilemanager alloc]init];
// 下面这几步很重要 通过文件管理器 来判读plist 文件是否存在! 如果不存在 我们就通过 [filemanager createfileatpath:plistpath contents:nil attributes:nil创建一个plist 并检测是否成功失败!存在后写入词典
如何存在plist 我们就 在 studentmessagedic 可变词典里保存在来色数据这样可以避免数据被覆盖问题
if(![filemanager fileexistsatpath:plistpath])
if(![filemanager createfileatpath:plistpathcontents:nilattributes:nil])
{
nslog(@"create file error");
}
else
nsdictionary* studentmessagedic = [nsdictionary dictionarywithobjectsandkeys:studentmessagearray,studentnumebr ,nil];
[studentmessagedic writetofile:plistpathatomically:yes];
else
nsmutabledictionary *studentmessagedic = [[nsmutabledictionary alloc]initwithcontentsoffile: plistpath];
[studentmessagedic setobject: studentmessagearray forkey:studentnumebr ];
[studentmessagedic writetofile:plistpathatomically:yes];
现在让我们调用方法吧! 打印路径plistpath 我们在沙盒里就会找到你的文件了如下图
-(void)prepareforsegue:(uistoryboardsegue *)segue sender:(id)sender
if (![studentnumbertextfield.tex tisequaltostring:@"" ])
savestudentmessageplist *save = [[savestudentmessageplist alloc]initwithstudentname:studentnametextfield.textstudentage:studentagetextfield.textstudentnumber:studentnumbertextfield.textstudentnation:studentnationtextfield.text];
三 对plist 经行读操作
我创建了一个只定义的tableview 来显示学生的信息
-(void)readstudentmessagefromplist
//创建文件管理器
nsfilemanager *filemanager = [nsfilemanager defaultmanager];
nsarray *path = nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask,yes);
nsstring *documentation = [path objectatindex:0];
//更改到待操作的目录下
[filemanager changecurrentdirectorypath:[documentationstringbyexpandingtildeinpath]];
nsstring *studentplistpath = [documentation stringbyappendingpathcomponent:@"student.plist"];
_studentmessagedic = [[nsmutabledictionary alloc]initwithcontentsoffile:studentplistpath];
nslog(@"%d", [_studentmessagedicallkeys].count);
然后在tableview上显示
#pragma mark - table view data source
- (nsinteger)numberofsectionsintableview:(uitableview *)tableview
// return the number of sections.
return 1;
- (nsinteger)tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section
// return the number of rows in the section.
return [[_studentmessagedicallkeys]count];
- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath
nsstring *keyvalue = [[_studentmessagedic allkeys]objectatindex:indexpath.row];
nsarray *studenmessagearr = [_studentmessagedic objectforkey:keyvalue];
static nsstring *cellidentifier =@"cell";
studentcell *cell = (studentcell *)[tableview dequeuereusablecellwithidentifier:@"studentcell"];
if (cell == nil)
if (cell == nil)
cell = [[studentcellalloc]initwithstyle: uitableviewcellstyledefault reuseidentifier:cellidentifier];
cell.name.text = [studenmessagearrobjectatindex:0];
cell.age.text = [studenmessagearrobjectatindex:1];
cell.number.text = [studenmessagearrobjectatindex:2];
cell.national.text = [studenmessagearrobjectatindex:3];
return cell;
当我们输入多个学生信息的时候我们会发现!数据根本不是按顺序显示的!(⊙_⊙)? 我们在plist表里明明看的是顺序写入的,但是显示的时候确是随机的!这时候应该想到的是排序! 好吧我把key 经行排序!
其实我们把红色 key 的那段函数改成下面的就可以了
nsarray *keyarray = [[_studentmessagedic allkeys]sortedarrayusingselector:@selector(compare:)];
//经行排序
nsstring *keyvalue = [ keyarray objectatindex:indexpath.row];
眼见为实 如图
!
四 这时候如果一个学生转学了!我们就要删除他的信息
这时候我们需要把以前的代码小改变下
我们把排序放在读取plist函数(-(void)readstudentmessagefromplist)里更好!并设置为全局变量
_keyarray = [[_studentmessagedic allkeys]sortedarrayusingselector:@selector(compare:)];
并把路径也改完全局的
在tableview的委托里进行删除
-(void)tableview:(uitableview *)tableview commiteditingstyle:(uitableviewcelleditingstyle)editingstyle forrowatindexpath:(nsindexpath *)indexpath
[self.tableviewbeg inupdates];
if (editingstyle ==uitableviewcelleditingstyledelete)
[_studentmessagedic removeobjectforkey:[_keyarray objectatindex:indexpath.row]];
[_studentmessagedic writetofile:_studentplistpath atomically:yes];
[self.tableview deleterowsatindexpaths:[nsmutablearray arraywithobject: indexpath
]withrowanimation:uitableviewrowanimationautomatic];
[self.tableview endupdates];
现在就只有小花了
看下效果吧
:
五 这时候一位老师输入一个新同学叫小米!但是不小心学号输入错了输入了小花的学号!
发现小花的信息出被替换了!这时候程序员又要做个判读了!
我在存入前遍历了下plist 如果存在就不进行写入操作 ,这样可以避免保存相同的数据!
// 创建plist
bool isorsava = yes;
nsstring *documentsdirectory = [paths objectatindex:0];
nsstring *plistpath = [documentsdirectory stringbyappendingpathcomponent:@"student.plist"];
nsfilemanager *filemanager = [[nsfilemanageralloc]init];
nsmutabledictionary *studentmessagedic = [nsmutabledictionarydictionarywithcontentsoffile:plistpath];
if ([studentmessagedic count] >= 1)
//遍历key
for (id objin [studentmessagedic allkeys])
nsstring *objstring = obj;
if ([[studentmessagearray objectatindex:2] isequaltostring:objstring])
{
isorsava = no; // 如果存在设置为no
nslog(@"学号以存在");
break;
}
if (isorsava == yes)
if(![filemanager fileexistsatpath:plistpath])
if(![filemanager createfileatpath:plistpath contents:nilattributes:nil])
nslog(@"create file error");
else
nsdictionary* studentmessagedic = [nsdictionary dictionarywithobjectsandkeys:studentmessagearray,studentnumebr ,nil];
[studentmessagedic writetofile:plistpathatomically:yes];
nsmutabledictionary *studentmessagedic= [[nsmutabledictionary alloc]initwithcontentsoffile:plistpath];
[studentmessagedic setobject:studentmessagearray forkey:studentnumebr ];
[studentmessagedic writetofile:plistpath atomically:yes];
}else
nsdictionary* studentmessagedic = [nsdictionarydictionarywithobjectsandkeys:studentmessagearray,studentnumebr ,nil];
nsmutabledictionary *studentmessagedic= [[nsmutabledictionaryalloc]initwithcontentsoffile:plistpath];
[studentmessagedic setobject: studentmessagearray forkey:studentnumebr ];
六 又过了几天 老师找到程序员说!我要可以修改学生的年龄!可是当时的需求没有要求呀!找知道可以修改不如用数据库 ,coredata ,可是这是一个很懒的程序员!我想直接对plist 经行修改吧!
点击cell 显示当前学生的年龄 改成你想改的年龄 然后返回首页 改成15 了 很懒的程序员只是加了几行代码
用到 atindexedsubscript 插入函数 把这个学习的年龄修改后在重新写入了plist
- (ibaction)savemessage:(id)sender
[_insterstudenmessage setobject:_agetextfield.text atindexedsubscript:1];
nsmutabledictionary *studendic = [[nsmutabledictionary alloc]init];
[studendic setvalue:_insterstudenmessageforkey:[_insterstudenmessage objectatindex:2]];
[studendic writetofile :_path atomically:yes];