1.如果对象是NSString、NSDictionary、NSArray、NSData、NSNumber等类型,可以直接用NSKeyedArchiver进行归档和恢复
2.不是所有对象都可以直接用这种方法进行归档,只有遵守了NSCoding协议的对象才可以
3.NSCoding协议有2个方法
encodeWithCoder:
每次归档对象时,都会调用这个方法。一般在这个方法里指定如果归档对象中的每一个实例变量,可以使用encodeObject:forKey:方法归档实例变量
initWithCoder:
每次从文件恢复(解码)对象时,都会调用这个方法。一般在这个方法里指定如何解码文件中的数据为对象的实例变量,可以使用decodeObject:forKey:方法解码实例变量。
实例:NSKeyedArchiver 归档Student对象
.h
#import <Foundation/Foundation.h>
@interface MJStudent : NSObject <NSCoding>
@property (nonatomic, copy) NSString *no;
@property (nonatomic, assign) double height;
@property (nonatomic, assign) int age;
@end
.m
#import "MJStudent.h"
@interface MJStudent()
@end
@implementation MJStudent
/**
* 将某个对象写入文件时会调用
* 在这个方法中说清楚哪些属性需要存储
*/
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.no forKey:@"no"];
[encoder encodeInt:self.age forKey:@"age"];
[encoder encodeDouble:self.height forKey:@"height"];
}
/**
* 从文件中解析对象时会调用
* 在这个方法中说清楚哪些属性需要存储
*/
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init]) {
// 读取文件的内容
self.no = [decoder decodeObjectForKey:@"no"];
self.age = [decoder decodeIntForKey:@"age"];
self.height = [decoder decodeDoubleForKey:@"height"];
}
return self;
}
@end
控制器存取:
- (IBAction)save {
// 1.新的模型对象
MJStudent *stu = [[MJStudent alloc] init];
stu.no = @"42343254";
stu.age = 20;
stu.height = 1.55;
// 2.归档模型对象
// 2.1.获得Documents的全路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.2.获得文件的全路径
NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
// 2.3.将对象归档
[NSKeyedArchiver archiveRootObject:stu toFile:path];
}
- (IBAction)read {
// 1.获得Documents的全路径
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// 2.获得文件的全路径
NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
// 3.从文件中读取MJStudent对象
MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@ %d %f", stu.no, stu.age, stu.height);
}