IOS_归档与解档

定义学生模型类(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];
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值