Steps:
1. The object needs to support serialization and deserialization must follow the Nscoding protocol
2, the realization of nscoding in the method
3, respectively, using Nskeyedarchiver and Nskeyedunarchiver class
For serialization and deserialization
#import <Foundation/Foundation.h>
#import "DSObject.h"
int main (int argc, const char * argv[]) {
Dsobject *srcobj = [[Dsobject alloc] init];
Srcobj.name = @ "Zhang San";
Srcobj.age = 32;
Srcobj.childnames = @[@ "Xiao Zhang 31", @ "Xiao Zhang 32", @ "Xiao Zhang 33";
NSLog (@ "%@", srcobj);
Serialization (there is a direct way to save to a file, or it can be saved to a file via NSData)
NSData *data = [Nskeyedarchiver archiveddatawithrootobject:srcobj];
[Data writetofile:@ "/users/ds/desktop/1.txt" atomically:yes];
Deserialization
NSData *data1 = [NSData datawithcontentsoffile:@ "/users/ds/desktop/1.txt"];
Dsobject *desobj = [Nskeyedunarchiver unarchiveobjectwithdata:data1];
NSLog (@ "%@", desobj);
[Srcobj release];
return 0;
}
Encoding (for serialization)
-(void) Encodewithcoder: (Nscoder *) Acoder {
[Acoder encodeobject:_name forkey:@ "name"];
[Acoder encodeinteger:_age forkey:@ "age"];
[Acoder encodeobject:_childnames forkey:@ "Childnames"];
}
Decoding (for deserialization)
-(ID) Initwithcoder: (Nscoder *) Adecoder {
if (self = [self init]) {
_name = [Adecoder decodeobjectforkey:@ "name"];
_age = [Adecoder decodeintegerforkey:@ "age"];
_childnames = [Adecoder decodeobjectforkey:@ "Childnames"];
[_name copy];
[_childnames retain];
}
return self;
}
Implementation of serialization and deserialization