归档和解归档除了用于NSString、NSNumber、NSArray、NSDictionary等对象和NSData之间的转换(见
点击打开链接),还可以用来保存别的对象,如保存界面上的view对象。
对象归档必须做两件事情:
1.对象必须遵守NSCoding协议
2.在对象中实现该协议的两个方法
//
属性编码
- (
void
)encodeWithCoder:(
NSCoder
*)aCoder{
[aCoder encodeObject:
self
.name forKey:
@"name"
];
[aCoder encodeInteger:
self
.age forKey:
@"age"
];
}
//
属性解码
- (
id
)initWithCoder:(
NSCoder
*)aDecoder{
self
= [
super
init
];
if
(
self
) {
self
.name = [aDecoder decodeObjectForKey:
@"name"
];
self
.age = [aDecoder decodeIntegerForKey:
@"age"
];
}
return
self
;
}
NSString、NSNumber、NSArray、NSDictionary以及UIView默认遵守了NSCoding协议。
// 一、
归档
NSArray *names = @[@“
A
"
,
@
“
B
"
,
@
“
C
"
,
@
“
D
"
]
;
// 1.
准备一个可变的
data
NSMutableData *data = [NSMutableDatadata];
// 2.
创建归档对象
NSKeyedArchiver
*arch = [[
NSKeyedArchiver
alloc
]
initForWritingWithMutableData
:data];
// 3.
把对象编码进去
[arch
encodeObject
:names
forKey
:
@"names"
];
// 4.
完成编码
[arch finishEncoding];
// 5、写入文件
[data writeToFile:@"/Users/tarena/Desktop/names"atomically:YES];
// 二、解归档
// 1、读入文件
NSData *data = [NSData dataWithContentsOfFile:@"/Users/tarena/Desktop/names"];
// 2、
创建反归档对象
NSKeyedUnarchiver *unArch = [[NSKeyedUnarchiveralloc]initForReadingWithData:data];
// 3、
解码
NSArray *names = [unArch decodeObjectForKey:@"names"];