One way to nscoding data persistence.
Data persistence, in fact, is to store the data on the network or hard disk, here is stored on the local hard disk, the application's local hard disk is a sandbox, the sandbox is actually a folder, it has 4 folders below. is the Documents,library,app package and TMP folder, documents are mainly stored in the user's long-term use of files, the Library has caches and preferences folder, the caches is stored in temporary files, Cache. The preferences inside is a preference setting. TMP inside is also a temporary file, but with the caches there is a difference, the app package is compiled after some files, package can not be modified.
Nscoding protocol only two methods, are require method, one is the class of its own transcoding, a reversal of the class object, return an object, we combat the use of this Protocol, to see if it works well, first write a custom student class:
@interfaceStudent:nsobject<nscoding>
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *id;
-(Student *) Initwithname:(nsstring*) newName
And: (NSString *) NewID;
@end
The student class needs to implement the protocol in the NSCODING,.M file:
@implementationStudent
@synthesize name = _name,id = _id;
Initialize Student class
-(Student *) Initwithname: (NSString *) NewName and: (NSString *) newid{
self = [super init];
if (self) {
Self.name = NewName;
Self.id= NewID;
}
return self;
}
Two attribute variables within the Student class are transcoded separately
-(void) Encodewithcoder: (Nscoder *) acoder{
[Acoder encodeObject:self.name forkey:@ "name"];
[Acoder encodeobject:self. idforkey:@ "ID"];
}
The two attribute variables were reversed according to the keyword, and finally returned an object of the student class.
-(ID) Initwithcoder: (Nscoder *) adecoder{
if (self = [super init]) {
Self.name = [Adecoder decodeobjectforkey:@ "name"];
self.id= [Adecoder decodeobjectforkey:@ "ID"];
}
return self;
}
@end
After the custom class student implements the Nscoding protocol, it can be converted to the archive, specifically:
Student *STU1 = [[Student alloc]initwithname:@ "124" and:@ "111"];//Student object Stu1
Student *STU2 = [[Student alloc]initwithname:@ "223" and:@ "222"];//Student object Stu2
Nsarray *stuarray =[nsarray arraywithobjects:stu1,stu2, nil];//Student Object array containing STU1 and STU2
NSData *studata = [Nskeyedarchiver archiveddatawithrootobject:stuarray];//archive
NSLog (@ "data =%@", studata);
Nsarray *stuarray2 =[nskeyedunarchiver unarchiveobjectwithdata:studata];//Reverse Archive
NSLog (@ "array2 =%@", stuArray2);
Nscoding archiving and anti-archiving of classes