////Student.h//ui16_ data Persistence////Created by Dllo on 15/8/19.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import <Foundation/Foundation.h> #pragma mark if you want to implement archiving and anti-archive operations, you need to sign a protocol first nscoding @interface Student : nsobject<nscoding>@property(nonatomic, copy)NSString*name;@property(nonatomic, copy)NSString*sex;@property(nonatomic,Assign)NsintegerAge@property(nonatomic, copy)NSString*hobby;//For these four properties, write a custom initialization method and a convenience builder-(Instancetype) Initwithname: (NSString*) name Sex: (NSString*) Sex Age: (Nsinteger) Age Hobby: (NSString*) hobby;+ (instancetype) Studentwithname: (NSString*) name Sex: (NSString*) Sex Age: (Nsinteger) Age Hobby: (NSString*) hobby;@end
////STUDENT.M//ui16_ data Persistence////Created by Dllo on 15/8/19.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import "Student.h" @implementation Student -(Instancetype) Initwithname: (NSString*) name Sex: (NSString*) Sex Age: (Nsinteger) Age Hobby: (NSString*) hobby{ Self=[SuperINIT];if( Self) {_age =age; _name =name; _hobby =hobby; _sex =sex; }return Self;} + (Instancetype) Studentwithname: (NSString*) name Sex: (NSString*) Sex Age: (Nsinteger) Age Hobby: (NSString*) hobby{Student *stu = [[Student alloc] initwithname:name sex:sex age:age Hobby:hobby];returnStu;}#pragma mark has signed the Nscoding agreement, two protocol methods need to be implemented, one to be used when archiving, and one to use when anti-archiving .- (void) Encodewithcoder: (Nscoder *) acoder{[Acoder encodeobject: Self. Nameforkey:@"Name"]; [Acoder Encodeinteger: Self. Ageforkey:@"Age"]; [Acoder Encodeobject: Self. Hobbyforkey:@"Hobbies"]; [Acoder Encodeobject: Self. Sexforkey:@"Gender"];//Use the Encode method to match the type of data}- (ID) Initwithcoder: (Nscoder *) adecoder{ Self= [SuperINIT];if( Self) {//data is re-compiled according to the previous key Self. Name= [Adecoder decodeobjectforkey:@"Name"]; Self. Age= [Adecoder decodeintegerforkey:@"Age"]; Self. Hobby= [Adecoder decodeobjectforkey:@"Hobbies"]; Self. Sex= [Adecoder decodeobjectforkey:@"Gender"]; }return Self;} - (void) Didreceivememorywarning {[SuperDidreceivememorywarning];//Dispose of any resources, can be recreated.}@end
////VIEWCONTROLLER.M//ui16_ data Persistence////Created by Dllo on 15/8/19.//Copyright (c) 2015 Zhozhicheng. All rights reserved.//#import "ViewController.h" #import "Student.h" @interface viewcontroller ()@end @implementation viewcontroller - (void) Viewdidload {[SuperViewdidload];additional setup after loading the view, typically from a nib. //iphone in order to ensure the absolute security of their data, the design of the sandbox file, each application is equipped with their own sandbox files, each run, the name of the folder will become a string without any regularity ///First parameter: current to go to that folder, go to documents file with NSDOCUEMTDIRECTORY,64, you can also go to the caches folder, corresponding to 68 lines ///second parameter: Access folder type, specify access is User folder ///third parameter: absolute path (YES), relative path (NO) //absolute path is used for the system, the system can find the folder according to the current path, we are the absolute path when manipulating the folder //relative path will only show the folder you want to go to, other parts are ~, tell the programmer which folder//Nsarray *sandbox =nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES);//NSLog (@ "%@", Sandbox[0]); //Sandbox in a total of three files //1. Is the documents file: mainly used to store the user wants to store some information, such as the collection of information or some of their own settings, so we do the collection function is to go to this folder to write files //2.library folder is convenient for program developers, the main operation of it inside the two folders, caches and preferences //caches: To save the cache file, Sdwebimage will add the image to the cache file, so clear the cache function is to delete this folder //preferences: General to save programmer settings information, such as Nsuserdefults will keep the data in this folder //3.tmp File: Temporary content for general storage //Before in the sandbox there is an. app file that has been removed in the new version //write Simple object to local, simple object refers to Nsstring,nsarray////1. Get the sandbox path by array first//Nsarray *sandbox = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);////Get the sandbox path from the array//NSString *sandboxpath =sandbox[0];//// to stitch a path to a file that is written, there are two ways to stitch////NSString *documentpath = [Sandboxpath stringbyappendingstring:@ "/Guyu. txt"];// //NSString *documentpath = [Sandboxpath stringbyappendingpathcomponent:@ "Guyu. xml"];//NSLog (@ "%@", documentpath);//NSString *STR = @ "The book Mountain has no royal road for the path, the work of the Endless bitter boat";//// write string to local///// first parameter: The path to save the file//// /second parameter: Protect the file Yes//// third parameter: encoding//// fourth parameter, error message//[str writetofile:documentpath atomically:yes encoding:nsutf8stringencoding Error:nil];if there is a corresponding file under the path, the original file will be overwritten, and if not, a new file is created///// read out the sandbox file//NSString *temostr = [NSString stringwithcontentsoffile:documentpath encoding:nsutf8stringencoding Error:nil]; //NSLog (@ "%@", temostr);//// write array to local//Nsarray *arr [email protected][@ "1", @ "2", @ "3", @ "4", @ "5", @ "6"];////Get the sandbox address through an array//Nsarray *sandbox = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);//// Save sandbox path with string//NSString *sandboxpath = sandbox[0];////to the file to be written stitching path//NSString *documentpath = [Sandboxpath stringbyappendingpathcomponent:@ "haha. plist"];//// write array to local//[arr Writetofile:documentpath atomically:yes];//NSLog (@ "%@", documentpath);// //// read out the array//Nsarray *temp = [Nsarray Arraywithcontentsoffile:documentpath];//NSLog (@ "%@", temp);//// write dictionary to local//Nsdictionary *dic = [nsdictionary dictionarywithobjectsandkeys:@ "1", @ "2", nil];//Nsarray *sandbox = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);//NSString *sandboxpath = sandbox[0];//NSString *documentpath = [Sandboxpath stringbyappendingpathcomponent:@ "hehe"];//[dic Writetofile:documentpath Atomically:yes];//NSLog (@ "%@", documentpath);// //Nsdictionary *temp = [Nsdictionary Dictionarywithcontentsoffile:documentpath];//NSLog (@ "%@", temp); //Complex object writes to local, mainly refers to our own created objects written locally, also called Archive and anti-archive operations //Create objects?//Student *STU1 = [Student studentwithname:@ "Zhang San" sex:@ "male" age:14 hobby:@ "Play"];////1. Get the sandbox path from an array//Nsarray *sandbox = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);////2. Intercepting a sandbox path with a string//NSString *sandboxpath = sandbox[0];////3. Stitching folder path, this folder extension is arbitrary//NSString *decomentpath = [Sandboxpath stringbyappendingpathcomponent:@ "student. avi"];//// Archive an object///// First parameter: the object to implement the archive//// second parameter: path//[Nskeyedarchiver archiverootobject:stu1 Tofile:decomentpath];//NSLog (@ "%@", Decomentpath);// ///Reverse archive//Student *newstu = [Nskeyedunarchiver Unarchiveobjectwithfile:decomentpath];//NSLog (@ "%@", newstu.name);//// creation of three students//Student *STU1 = [Student studentwithname:@ "Zhang San" sex:@ "male" age:14 hobby:@ "Play"];//Student *STU2 = [Student studentwithname:@ "John Doe" sex:@ "female" age:15 hobby:@ "Sleep"];//Student *STU3 = [Student studentwithname:@ "God six" sex:@ "male" age:16 hobby:@ "singing"];//Nsarray *array = @[stu1,stu2,stu3];// //Nsarray *sandbox = Nssearchpathfordirectoriesindomains (nsdocumentdirectory, 1, YES);//NSString *sandboxpath = sandbox[0];//// Stitching file path//NSString *documentpath = [Sandboxpath stringbyappendingpathcomponent:@ "Cao June. plist"];//// archive Operations//[Nskeyedarchiver Archiverootobject:array Tofile:documentpath];//NSLog (@ "%@", documentpath);// ///Reverse archive, traverse student's name//Nsarray *arr = [Nskeyedunarchiver Unarchiveobjectwithfile:documentpath];//For (Student *temp in arr) {//NSLog (@ "%@", temp.name);// }#warning Summary: Steps for data persistence //1. Specify the folder to go to //2. Receiving a path with a string //3. stitching file path //4. Writing to local or archive operations //Note; if it is a complex object archive, to sign the Nscoding protocol, and implement the two protocol methods, the complex object placed in the array archive also need to sign the agreement//Nsuserdefaults *defaults = [Nsuserdefaults standarduserdefaults];//[Defaults setobject:@ "123456" forkey:@ "password"];//Nsarray *sandbox = Nssearchpathfordirectoriesindomains (nsdocumentdirectory, 1, YES);//NSLog (@ "%@", Sandbox[0]);//NSLog (@ "%@", [Defaults objectforkey:@ "password"]); //nsuserdefaults generally store small data, such as strings, which are used in a similar dictionary //The folder is manipulated by the file Manager Nsarray*sandbox = Nssearchpathfordirectoriesindomains (NSDocumentDirectory,1,YES);NSString*sandboxpath =sandbox[0];//Create a File Manager Nsfilemanager*manager = [NsfilemanagerDefaultmanager];//Stitch a path to the folder you want to create NSString*filepath = [Sandboxpath stringbyappendingpathcomponent:@"Guyu"];//The name of the folder does not require an extension //Create a folder through the manager[Manager Createdirectoryatpath:filepath Withintermediatedirectories:YESAttributesNilErrorNil];NSLog(@"%@", FilePath);//write a string to the folder NSString*documentpath = [FilePath stringbyappendingpathcomponent:@"string. txt"];NSString*STR = @"I am a string"; [Str writetofile:documentpath atomically:YESEncoding:nsutf8stringencoding Error:Nil];//Removing folders//[manager Removeitematpath:filepath Error:nil];// //Clear Cache Nsarray*cache = Nssearchpathfordirectoriesindomains (Nscachesdirectory,1,YES);NSString*cachepath =cache[0]; [Manager Removeitematpath:cachepath Error:Nil];}@end
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
IOS ui16_ Data Persistence