IOS数据存储NSKeyedArchiver的使用

这种方式的存储是采用归档的形式来保存数据。

例:
1.新建一个Student类,给出两个属性:name、age。并要遵守NSCoding协议;

/* Students.h */ 
#import <Foundation/Foundation.h>

@interface Students : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSUInteger age;

@end

2. 要实现这两个方法:

/* Students.m */
#import "Students.h"

@implementation Students

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeInteger:_age forKey:@"age"];
}
- (id)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeIntegerForKey:@"age"];
    }    
    return self;    
}
@end

3. 在控制器里开始写数据:

/* ViewController.m */
#import "ViewController.h"
#import "Students.h"

@interface ViewController ()
@property (nonatomic, strong) NSMutableDictionary *studentDict; //保存所有student信息的字典
@property (nonatomic, copy) NSString *fullPath; //保存的文件的全路径
@end

@implementation ViewController
/* 懒加载 */
- (NSMutableDictionary *)studentDict{
    if (_studentDict == nil) {
        _studentDict = [NSMutableDictionary dictionary];
    }
    return _studentDict;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    Students *student1 = [[Students alloc] init];
    student1.name = @"张三";
    student1.age = 18;

    Students *student2 = [[Students alloc] init];
    student2.name = @"李四";
    student2.age = 19;

    [self.studentDict setObject:student1 forKey:@"student1"]; 
    [self.studentDict setObject:student2 forKey:@"student2"]; //写数据时必须用self.studentDict(会调用set方法),如果用_studentDict是保存不进去的(get方法不能写数据)

    /* 获取沙盒路径 */
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    /* 生成全路径:给要保存的文件取个别名,并拼接在沙盒路径后面作为全路径 */
    NSString *fullPath = [path stringByAppendingPathComponent:@"stdents.data"];
    /* 保存数据 */
    [NSKeyedArchiver archiveRootObject:_studentDict toFile:fullPath];
    /* 保存全路径 */
    _fullPath = fullPath;
}

/* 点击屏幕,读取数据,打印结果 */
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{

    /* 读取数据 */
    NSDictionary *dict = [NSDictionary dictionary];
    dict = [NSKeyedUnarchiver unarchiveObjectWithFile:_fullPath];

    Students *p1 = [[Students alloc] init];
    p1 = [dict objectForKey:@"student1"];
    Students *p2 = [[Students alloc] init];
    p2 = [dict objectForKey:@"student2"];

    NSLog(@"sutdent1:姓名:%@--年龄:%ld", p1.name, p1.age);
    NSLog(@"sutdent2:姓名:%@--年龄:%ld", p2.name, p2.age);

}
@end

打印出结果:
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值