model归档

本文介绍了如何在Objective-C中实现NSCoding协议,对自定义的Student模型进行归档和反归档操作,包括签订NSCoding协议、编码模型属性、解码模型以及实际的归档和反归档步骤。通过这些步骤,可以将模型数据存储到本地并读取。
摘要由CSDN通过智能技术生成
#import <Foundation/Foundation.h>

#warning 归档第一步:让model签订NSCoding协议
@interface Student : NSObject<NSCoding>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,assign)NSInteger age;
@property(nonatomic,copy)NSString *gender;
@end


#import "Student.h"

@implementation Student

#warning 归档第二步:对model属性进行编码
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.gender forKey:@"gender"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
#warning 归档第三步:对model进行解码
-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];
    if (self) {
        self.name =
        [aDecoder decodeObjectForKey:@"name"];
        self.gender =
        [aDecoder decodeObjectForKey:@"gender"];
        self.age =
        [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}


@end


 /***************写入model*************************/
    //缓存自定义model模型数据
    //需要使用iOS中归档/反归档,专门来存储model数据到本地
   
#warning 归档第四步:对model进行归档操作
    Student *stu = [[Student alloc]init];
    stu.name = @"大水杯";
    stu.gender = @"男";
    stu.age = 18;
    NSString *archiverPath = [documentPath stringByAppendingPathComponent:@"student"];
   
    //归档类
    BOOL result3 =
    [NSKeyedArchiver archiveRootObject:stu toFile:archiverPath];
   
    if (result3) {
        NSLog(@"归档成功");
    }else
    {
        NSLog(@"归档失败");
    }
   
    //反归档取出model数据
    Student *stu1 = [NSKeyedUnarchiver unarchiveObjectWithFile:archiverPath];
    NSLog(@"name = %@ %@ %ld",stu1.name,stu1.gender,stu1.age);
    /***************写入model*************************/
   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值