NSCoder类
1,概述
将对象的实例变量和其他数据编码为数据块,然后将他们存在到磁盘当中;以后将这些数据块读回到内存中,并且还基于保存的数据创建新的对象,也称序列化或反序列化。
2,用法
a,首先,定义一个类,使其遵守<NSCoding>协议
@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 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;
}
实现<NSCoding>协议中的-encoderWithCoder和-initWithCoder
接以上代码
-(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,再次,使用该类定义一个对象,初始化它。
Thingie *thing1;
thing1=[[Thingie alloc]
initWithName:@"thing1"
magicNumber:42
shoeSize:10.5];
c,定义一个NSData对象,并使用类方法:NSKeydArchiver对对象进行编码后赋值给NSData对象。
NSData *freezeDried;
freezeDried=[NSKeyedArchiver archivedDataWithRootObject:thing1];
d,如果愿意,可以将NSData对象存储到磁盘上
[freezeDried writeToFile:@"/tmp/verbiage.txt"
atomically:YES];
f,解码NSData
thing1=[NSKeyedUnarchiver unarchiverObjectWithData:freezeDried];
3,注意点
如上所示例中,NSMultableArray对象subThingies可以存放各种对象,但是不能存储NSlog类,因为它不能检测对象循环。