Nscoder Class 1, overview
The object's instance variables and other data are encoded as blocks of data, then they are present to disk, later read back into memory, and new objects are created based on the saved data, also known as serialization or deserialization.
2, usage
A, first, define a class that adheres to the <NSCoding> protocol
@interface Thingie:nsobject <nscoding>{
NSString *name;
int magicnumber;
float shoesize;
Nsmutablearray *subthingies;
}
@property (copy) NSString *name;
@property int magicnumber;
@property float shoesize;
@property (retain) Nsmutablearray *subthingies;
-(ID) Initwithname: (NSString *) n
MagicNumber: (int) mn
Shoesize: (float) SS;
@end//interface Thingie
Implementation class
@implementation Thingie
@synthesize name;
@synthesize MagicNumber;
@synthesize shoesize;
@synthesize subthingies;
-(ID) Initwithname: (NSString *) n
MagicNumber: (int) mn
Shoesize: (float) ss{
if (Self==[super init]) {
Self.name=n;
SELF.MAGICNUMBER=MN;
Self.shoesize=ss;
Self.subthingies=[nsmutablearray array];
}
return self;
}
Implementation of-encoderwithcoder and-initwithcoder in <NSCoding> agreements
Connect to the above code
-(void) Encoderwithcoder: (nscoder*) coder{
[Coder Encodeobject:name
forkey:@ "Name"];
[Coder Encodeobject:magicnumber
forkey:@ "MagicNumber"];
[Coder Encodeobject:shoesize
forkey:@ "Shoesize"];
[Coder Encodeobject:subthingies
forkey:@ "Subthingies"];
}//encodewithcoder
-(ID) Initwithcoder: (Nscoder *) decoder{
if (Self=[super init]{
Self.name=[decoder decodeobjectforkey:@ "name"];
Self.magicnumber=[decoder decodeintforkey:@ "MagicNumber"];
Self.shoesize=[decoder decodefloatforkey:@ "Shoesize"];
Self.subthingies=[decoder decodeobjectforkey:@ "Subthingies"];
}
return self;
}//initwithcoder
b, again, use the class to define an object and initialize it.
Thingie *thing1;
Thing1=[[thingie Alloc]
initwithname:@ "Thing1"
Magicnumber:42
shoesize:10.5];
C, define a NSData object and use the class method: Nskeydarchiver assigns the object to the NSData object after it is encoded.
NSData *freezedried;
Freezedried=[nskeyedarchiver Archiveddatawithrootobject:thing1];
D, if you prefer, you can store the NSData object on disk
[FreezeDried writetofile:@ "/tmp/verbiage.txt"
Atomically:yes];
F, Decode NSData
Thing1=[nskeyedunarchiver unarchiverobjectwithdata:freezedried];
3, attention.
As in the example above, the Nsmultablearray object subthingies can hold various objects, but the NSLog class cannot be stored because it cannot detect object loops.
OBJECTIVE-C diary-The Encoding object properties