《IOS开发系列教程》序列化反序列化对象
Cocoa touch提供了序列化和反序列化的方法:
archiveRootObject
unarchiveObjectWithFile
使用这2个方法之前,要保证你的对象是实现了NSCoding协议,例如你定义了一个类,
在头文件中:
@interface myClass : NSObject <NSCoding>
在实现文件中:
@implementation
-(void)encodeWithCoder:(NSCoder *)encoder
{
}
- (id)initWithCoder:(NSCoder *)decoder
{
}
下面给出了一个列子:
-(void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:self.difficulty forKey:@"difficulty"];
[encoder encodeObject:self.language forKey:@"language"];
[encoder encodeObject:self.category forKey:@"category"];
[encoder encodeObject:self.playerType forKey:@"playerType"];
}
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
self.difficulty = [decoder decodeObjectForKey:@"difficulty"];
self.language = [decoder decodeObjectForKey:@"language"];
self.category = [decoder decodeObjectForKey:@"category"];
self.playerType = [decoder decodeObjectForKey:@"playerType"];
}
return self;
}
下面是将对象序列化写进文件,然后在反序列化从文件读出
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"];
NSMutableArray *myObject=[NSMutableArray array];
[myObject addObject:self.settings];
这里是写
[NSKeyedArchiver archiveRootObject:myObject toFile:appFile];
这里是读
NSMutableArray* myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile];
版权所有,禁止转载. 如需转载,请先征得博主的同意,并且表明文章转载自:IT夜班车,否则按侵权处理.