I. Archiving and unarchiving in the nscoding agreement
(1) Archiving an object that will record all properties of this object to filesystem;
(2) unarchiving an object and re-creates the object from data.
The strength of the class to archiving and unarchiving, to comply with the Nscoding protocol, and to achieve the following two methods:
@protocol nscoding-(void) Encodewithcoder: (nscoder*) Acoder; -(Instancetype) Initwithcoder: (nscoder*) Acoder; @end
Cases:
//Save-(void) Encodewithcoder: (nscoder*) acoder{[Acoder encodeObject:self.itemName forkey:@"ItemName"]; [Acoder encodeInt:self.valueInDollars Forkey:@"Valueindollars"];}//Take-(Instancetype) Initwithcoder: (nscoder*) acoder{ Self=[Super Init]; if(self) {_itemname= [Adecoder Decodeobjectforkey:@"ItemName"]; _valueindollars= [Adecoder Decodeintforkey:@"Valueindollars"]; } returnSelf ; }
In a similar way,
XIB file is saved, that is, the views archived into XIB file;
When the application starts, unarchive the views from the Xib file.
Second, the use of Nscoder sub-class in the sandbox access
The sandbox of the application is a directory that includes Documents, the Library (which is not deleted when the application exits), and TMP (which is deleted when the application exits).
Subclass of Nscoder, this refers to the two classes of Nskeyedarchiver and Nskeyedunarchiver.
Cases:
//generate file path-(NSString *) Itemarchivepath {Nsarray*documentdirectories =Nssearchpathfordirectoriesindomains (Nsdocumentdirectory,nsuserdomainmask,yes); NSString*documentdirectory =[Documentdirectories Firstobject]; return[Documentdirectory stringbyappendingpathcomponent:@"items.archive"];}//Save-(BOOL) saveChanges {nsstring*path =[self itemarchivepath]; return[Nskeyedarchiver archiverootobject:xxx tofile:path];}//Take-(instancetype) initprivate { self=[Super Init]; if(self) {nsstring*path =[self itemarchivepath]; _privateitem=[Nskeyedunarchiver Unarchiveobjectwithfile:path]; } returnSelf ;}
The process of Nskeyedarchiver the object is divided into two steps: (1) First call Encodewithcoder to encode the variable to Nskeyedarchiver, and (2) to the path.
Third, write filesystem with NSData
Cases:
-(nsstring*) Imagepathforkey: (nsstring*) key{Nsarray*documentdirectories =....; NSString*documentdirectory = ...; return[Documentdirectory Stringbyappendingpathcomponent:key];}//WriteNSString ImagePath =[self imagepathforkey:key]; NSData*data = uiimagejpegrepresentation (image,0.5); [Data Writetofile:imagepath Atomically:yes];//Delete[[Nsfilemanager Defaultmanager] Removeitematpath:imagepath Error:nil];//ReadUIImage *image = [UIImage Imagewithcontentoffile:imagepath];
Where Nsfilemanager can acquire, create, copy, and move files and directories.
Objective-c Data Saving and reading