数据存储(NSCoding)

NSCoding 是归档与解档的意思.
1.首先要获取存储的沙盒里,必须获取沙盒的路径.

/**沙盒的路径, 要将stu.data文件存储的Documents文件夹中,stringByAppendingPathComponent这个方法不用再拼接"/"*/
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"stu.data"];

/*创建数据模型/
Person 父类 属于NSObject
Strudent 子类 属于 Person的子类

#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>/**这里必须采用NSCoding这个协议*/
/**姓名*/
@property (strong, nonatomic) NSString *name;
/**年龄*/
@property (assign, nonatomic) NSInteger age;
@end
/**.m文件,实现NSCoding协议*/
#import "Person.h"

@implementation Person
/**当归档的时候会调用*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
    /**把属性归档起来,并设置key*/
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}
/**当解档的时候用调用*/
- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]){
    /**根据key解档存储的文件*/
    self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
@end
/**strudent类*/
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Strudent : Person
@property (strong, nonatomic) NSString *no;
@property (assign, nonatomic) NSInteger store;
@end
/**.m文件实现NSCoding协议*/
#import "Strudent.h"

@implementation Strudent
/**归档的实现的方法*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
/**继承父类后,首先要先调用父类的方法传入aCoder*/
    [super encodeWithCoder:aCoder];
    [aCoder encodeObject:self.no forKey:@"no"];
    [aCoder encodeInteger:self.store forKey:@"store"];
}
/**解档实现的方法*/
- (id)initWithCoder:(NSCoder *)aDecoder{
- /**继承父类后,首先要先调用父类的方法传入aDecoder*/
    if (self = [super initWithCoder:aDecoder]) {
       self.store = [aDecoder decodeIntegerForKey:@"store"];
       self.no = [aDecoder decodeObjectForKey:@"no"];
    }
    return self;
}
@end

保存

 /**新建数据模型*/
    Strudent *stu = [[Strudent alloc] init];
    stu.name = @"xingzai";
    stu.age = 27;
    stu.no  = @"68";
    stu.store = 100;

    [NSKeyedArchiver archiveRootObject:stu toFile:path];
    NSLog(@"%@",path);

读取

  Strudent *stu =  [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    NSLog(@"%@- %d -- %@ --%d",stu.name,stu.age,stu.no,stu.store);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值