iOS开发-本地存储(偏好设置,Plist,归档)
程序员文章站
2022-03-26 08:47:25
1. NSUserDefaults 2. Plist 3. 归档、解档 ......
1. nsuserdefaults
//todo: 1.nsuserdefaults nsuserdefaults类除了可以存储数组、字典、nsdata外,还可以直接存储oc基本类型属性。但是不能直接作用到自定义对象. [[nsuserdefaults standarduserdefaults] setobject:@"" forkey:@""];//设置初始值 [[nsuserdefaults standarduserdefaults] synchronize];//进行同步 [[nsuserdefaults standarduserdefaults] objectforkey:@""];//取值
2. plist
//todo: 2.plist文件 //1.根据已有plist文件取值 nsstring *pathstring = [[nsbundle mainbundle] pathforresource:@"property list" oftype:@"plist"]; //如果plist文件是一个nsarray,用数组取 nsarray *array = [nsarray arraywithcontentsoffile:pathstring]; //如果plist文件是一个nsdictionary,用字典取 nsdictionary *dictionary = [nsdictionary dictionarywithcontentsoffile:pathstring];
//2.创建plist文件 nsarray *homedirectory = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *documentstring = homedirectory[0]; nsstring *documentpath = [documentstring stringbyappendingpathcomponent:@"gcd.plist"]; nsfilemanager *filemanager = [nsfilemanager defaultmanager]; [filemanager createfileatpath:documentpath contents:nil attributes:nil]; nsarray *filearray = @[@{@"name":@"one"},@{@"name":@"two"}]; [filearray writetofile:documentpath atomically:yes];//写入数据 nsarray *readarray = [nsarray arraywithcontentsoffile:documentpath];//读取数据
3. 归档、解档
//todo: 3.归档/解档 archivemodel *model = [[archivemodel alloc]init]; model.name = @"小明"; model.age = @"18"; model.sex = @"男"; nsarray *patharray = nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes); nsstring *filepath = [patharray[0] stringbyappendingpathcomponent:@"model"]; /* 一.只归档一个对象 [nskeyedarchiver archiverootobject:model tofile:filepath]; */ /* 一.只解档一个对象 if ([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) { //路径存在 archivemodel *readmodel = [nskeyedunarchiver unarchiveobjectwithfile:filepath]; nslog(@"解档:%@",readmodel); } */ //二.归档多个对象 nsmutabledata *data = [[nsmutabledata alloc]init]; nskeyedarchiver *keyedarchiver = [[nskeyedarchiver alloc]initforwritingwithmutabledata:data]; [keyedarchiver encodeobject:model forkey:@"model"]; //[keyedarchiver encodeobject:model forkey:@"key1"]; //[keyedarchiver encodeobject:model forkey:@"key2"]; [keyedarchiver finishencoding]; if ([data writetofile:filepath atomically:yes]) { nslog(@"归档成功"); } //二.解档多个对象 if ([[nsfilemanager defaultmanager] fileexistsatpath:filepath]) { nsdata *data = [nsdata datawithcontentsoffile:filepath]; nskeyedunarchiver *keyedunarchive = [[nskeyedunarchiver alloc]initforreadingwithdata:data]; archivemodel *readmodel = [keyedunarchive decodeobjectforkey:@"model"]; //archivemodel *readmodel = [keyedunarchive decodeobjectforkey:@"key1"]; //archivemodel *readmodel = [keyedunarchive decodeobjectforkey:@"key2"]; [keyedunarchive finishdecoding]; }
上一篇: 想起邻居儿子结婚的一个笑话