定义学生模型类(Student):
模型 .h 文件
@interface Student : NSObject<NSCoding>
@property (strong, nonatomic) NSDictionary *character;
@property (assign, nonatomic) NSInteger age;
@property (copy, nonatomic) NSString *name;
@end
模型 .m 文件
@implementation Student
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]) {
self.character = [aDecoder decodeObjectForKey:@"character"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.character forKey:@"character"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeObject:self.name forKey:@"name"];
}
@end
实现操作:
// 归档存值
- (BOOL)saveStudent:(Student *)student{
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:student forKey:@"Student_Key"];
[archiver finishEncoding];
return [data writeToFile:[self getFilePathWithModelKey:@"Data_Name"] atomically:YES];
}
// 解档取值
- (Student *)takeOut{
NSData *_data = [[NSData alloc] initWithContentsOfFile:[self getFilePathWithModelKey:@"Data_Name"]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:_data];
Student *mStudent = [unarchiver decodeObjectForKey:@"Student_Key"];
[unarchiver finishDecoding];
return mStudent;
}
// 得到Document目录
-(NSString *) getFilePathWithModelKey:(NSString *)modelkey
{
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[array objectAtIndex:0] stringByAppendingPathComponent:modelkey];
}