关闭

IOS数据存储NSKeyedArchiver的使用

标签: ios数据存储数据存储ios数据存储
119人阅读 评论(0) 收藏 举报
分类:

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

例:
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:121次
    • 积分:14
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档