您的位置:首页 > 移动开发 > IOS开发

IOS_归档与解档

2015-12-19 15:49 465 查看
定义学生模型类(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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: