IOS ui16_ Data Persistence

Source: Internet
Author: User
Tags tmp file

////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 assumes that it is necessary to sign an agreement to implement an archive and an anti-archive operation 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 self-defined initialization method and a convenience constructor-(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 for archival use, and one for anti-filing .- (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) {//The data will be re-compiled back by 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 execution, the name of the directory will become a no matter what the law of the string    ///First: To go to that directory, go to the documents file with NSDOCUEMTDIRECTORY,64, you can also go to the caches directory, the corresponding 68 lines    ///second: The type of directory to be interviewed, and the user directory for the specified interview    //Third parameter: absolute path (YES), relative path (NO)    //absolute path is used for the system, the system can find the directory according to the current path, we are the absolute path when manipulating the directory    The //relative path only shows the directory to go, the rest is ~, tells the program which directory the ape is going to//Nsarray *sandbox =nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES);//NSLog (@ "%@", Sandbox[0]);    //Sandbox a co-owned 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 directory to write files    The //2.library directory is for the convenience of the developer of the program, the main operation of its two directories, 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 the directory    //preferences: General to save the information of the program ape settings, for example Nsuserdefults will keep the data in this directory    //3.tmp file: General Storage temporary content    //before another. app file in the sandbox has been removed in the new version number    //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 number of parameters, error message//[str writetofile:documentpath atomically:yes encoding:nsutf8stringencoding Error:nil];///// assuming the corresponding file is in the path, the original file will be overwritten, assuming no new file is created///// read out the sandbox file//NSString *temostr = [NSString stringwithcontentsoffile:documentpath encoding:nsutf8stringencoding error:nil];< /c2>//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 directory path, this directory extension is arbitrary//NSString *decomentpath = [Sandboxpath stringbyappendingpathcomponent:@ "student. avi"];//// Archive an object/////First parameter: object to be implemented for archiving//// second number of references: 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. Assigning to that directory    //2. Receiving a path with a string    //3. stitching file path    //4. Writing to local or archive operations    //note; Assuming a complex object archive, to sign the Nscoding protocol, and to implement the two protocol methods, the complex objects 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 way to dictionaries.    //The directory is operated 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 directory you want to create    NSString*filepath = [Sandboxpath stringbyappendingpathcomponent:@"Guyu"];//directory name does not require an extension    //creation of catalogs through the manager[Manager Createdirectoryatpath:filepath Withintermediatedirectories:YESAttributesNilErrorNil];NSLog(@"%@", FilePath);//write a string to the directory    NSString*documentpath = [FilePath stringbyappendingpathcomponent:@"string. txt"];NSString*STR = @"I am a string"; [Str writetofile:documentpath atomically:YESEncoding:nsutf8stringencoding Error:Nil];//Remove directory//[manager Removeitematpath:filepath Error:nil];//    //Clear Cache    Nsarray*cache = Nssearchpathfordirectoriesindomains (Nscachesdirectory,1,YES);NSString*cachepath =cache[0]; [Manager Removeitematpath:cachepath Error:Nil];}@end

IOS ui16_ Data Persistence

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.