实现序列化和反序列化
// 步骤:
// 1、对象需要支持序列化和反序列化必须遵循NSCoding协议
// 2、实现NSCoding中的方法
// 3、分别使用NSKeyedArchiver和NSKeyedUnarchiver类
// 来进行序列化和反序列化
#import <Foundation/Foundation.h>
#import "DSObject.h"
int main(int argc, const char * argv[]) {
DSObject *srcObj = [[DSObject alloc] init];
srcObj.name = @"张三";
srcObj.age = 32;
srcObj.childNames = @[@"小张三1", @"小张三2", @"小张三3"];
NSLog(@"%@", srcObj);
// 序列化(有直接的方法保存到文件,也可以通过NSData保存到文件)
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:srcObj];
[data writeToFile:@"/Users/DS/Desktop/1.txt" atomically:YES];
// 反序列化
NSData *data1 = [NSData dataWithContentsOfFile:@"/Users/DS/Desktop/1.txt"];
DSObject *desObj = [NSKeyedUnarchiver unarchiveObjectWithData:data1];
NSLog(@"%@", desObj);
[srcObj release];
return 0;
}
// 编码(用于序列化)
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_name forKey:@"name"];
[aCoder encodeInteger:_age forKey:@"age"];
[aCoder encodeObject:_childNames forKey:@"childNames"];
}
// 解码(用于反序列化)
- (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;
}