iOS中归档对象的创建,数据写入与读取
归档(archiving)是指另一种形式的序列化,但它是任何对象都可以实现的更常规的模型。专门编写用于保存数据的任何模型对象都应该支持归档。比属性列表多了很良好的伸缩性,因为无论添加多少对象,将这些对象写入磁盘的方式都相同。但使用属性列表,工作量会随着添加对象而增加。
创建一个工程,为ViewController。
新建两个类为NJperson
NJperson.h
#import <Foundation/Foundation.h>
// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface NJPerson : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double height;
@end
NJperson.m
#import "NJPerson.h"
@implementation NJPerson
// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
- (void)encodeWithCoder:(NSCoder *)encoder
{
NSLog(@"NJPerson encodeWithCoder");
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInteger:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"heigth"];
}
// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
- (id)initWithCoder:(NSCoder *)decoder
{
NSLog(@"NJPerson initWithCoder");
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntegerForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"heigth"];
}
return self;
}
_______在项目中创建两个按钮:一个为save,一个为read。
- (void)saveBtnClick:(id)sender{
NJStudent *stu = [[NJStudent alloc] init];
stu.name = @"lnj";
stu.age = 28;
stu.height = 1.8;
// 2.获取文件路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
NSLog(@"path = %@", path);
// 3.将自定义对象保存到文件中
[NSKeyedArchiver archiveRootObject:stu toFile:path];
}
- (void)readBtnClick:(id)sender {
// 1.获取文件路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
// 2.从文件中读取对象
// NJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}
对数据对象进行归档和取消归档的另外一个例子如下:
BIDFourLines.h
#import <Foundation/Foundation.h>
@interface BIDFourLines : NSObject<NSCoding,NSCopying>
@property(copy,nonatomic)NSArray *lines;
@end
BIDFourLines.m
#import "BIDFourLines.h"
static NSString *const kLinesKey = @"kLinesKey";
@implementation BIDFourLines
-(id)initWithCoder:(NSCoder *)aDecoder{ //归档
self = [super init];
if (self) {
self.lines = [aDecoder decodeObjectForKey:kLinesKey];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder{ //解档
[aCoder encodeObject:self.lines forKey:kLinesKey];
}
#pragma mark copying
-(id)copyWithZone:(NSZone *)zone{
BIDFourLines *copy = [[[self class]allocWithZone:zone]init];
NSMutableArray *linesCopy = [NSMutableArray array];
for (id line in self.lines) {
[linesCopy addObject:[line copyWithZone:zone]];
}
copy.lines = linesCopy;
return copy;
}
@end
#import "ViewController.h"
#import "BIDFourLines.h"
static NSString *const kRootKey = @"kRootKey";
@interface ViewController ()
@property(strong,nonatomic)IBOutletCollection(UITextField)NSArray *lineFields;
@end
@implementation ViewController
-(NSString *)dataFilePath{
//查找Document目录并在其后附加数据文件的文件名,这样就得到了数据文件的完整的路径
NSArray *paths = NSSearchPathForDirectoriesInDomains(
NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
return [documentDirectory stringByAppendingPathComponent:@"data.archive"];
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//
NSString *filePath = [self dataFilePath];
//检查数据文件在不在
if ([[NSFileManager defaultManager]fileExistsAtPath:filePath]) {
NSData *data = [[NSMutableData alloc]initWithContentsOfFile:filePath];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
BIDFourLines *fourLines = [unarchiver decodeObjectForKey:kRootKey];
[unarchiver finishDecoding];
for (int i = 0; i < 4; i++) {
UITextField *theField = self.lineFields[i];
theField.text = fourLines.lines[i];
}
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
}
//应用在终止运行或者进去后台之前保存数据
-(void)applicationWillResignActive:(NSNotification *)notification{
NSString *filePath = [self dataFilePath];
BIDFourLines *fourLines = [[BIDFourLines alloc]init];
fourLines.lines = [self.lineFields valueForKey:@"text"];
NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:fourLines forKey:kRootKey];
[archiver finishEncoding];
[data writeToFile:filePath atomically:YES];
}
@end
iOS中归档对象的创建,数据写入与读取的更多相关文章
- iOS中plist的创建,数据写入与读取
iOS中plist的创建,数据写入与读取 Documents:应用将数据存储在Documents中,但基于NSuserDefaults的首选项设置除外Library:基于NSUserDefaults的 ...
- 蜗牛爱课- iOS中plist的创建,数据写入与读取
iOS中plist的创建,数据写入与读取功能创建一个test.plist文件-(void)triggerStorage{ NSArray *paths=NSSearchPathForDirect ...
- iOS——plist的创建,数据写入与读取
iOS中plist的创建,数据写入与读取 Documents:应用将数据存储在Documents中,但基于NSuserDefaults的首选项设置除外Library:基于NSUserDefaults的 ...
- iOS中常用的四种数据持久化方法简介
iOS中常用的四种数据持久化方法简介 iOS中的数据持久化方式,基本上有以下四种:属性列表.对象归档.SQLite3和Core Data 1.属性列表涉及到的主要类:NSUserDefaults,一般 ...
- HibernateSessionFactory类中Session对象的创建步骤
HibernateSessionFactory类中Session对象的创建步骤: 1.初始化Hibernate配置管理类Configuration 2.通过Configuration类实例创建Sess ...
- 在C#程序中,创建、写入、读取XML文件的方法
一.在C#程序中,创建.写入.读取XML文件的方法 1.创建和读取XML文件的方法,Values为需要写入的值 private void WriteXML(string Values) { //保存的 ...
- UWP入门(十)--创建、写入和读取文件
原文:UWP入门(十)--创建.写入和读取文件 核心的 API github代码 StorageFolder 类 StorageFile 类 FileIO 类 使用 StorageFile 对象读取和 ...
- iOS——归档对象的创建,数据写入与读取
归档(archiving)是指另一种形式的序列化,但它是任何对象都可以实现的更常规的模型.专门编写用于保存数据的任何模型对象都应该支持归档.比属性列表多了很良好的伸缩性,因为无论添加多少对象,将这些对 ...
- iOS中偏好设置的创建,数据写入与读取
NSUserDefaults与NSDictinary? 应用通过NSUserDefaults用键值对的方式来读取和保存偏好设置数据,与通过键从NSDictionary对象中获取数据一样,不同之处在于N ...
随机推荐
- Effective Java 20 Prefer class hierarchies to tagged classes
Disadvantage of tagged classes 1. Verbose (each instance has unnecessary irrelevant fields). 2. Erro ...
- TCP 连接的 TIME_WAIT 过多 导致 Tomcat 假死
最近系统二次开发之后,发现使用的 Tomcat 7 会经常假死.前端点击页面无任何反应,打开firebug,很多链接一直在等待服务器的反应.查看服务器的状态,CPU占用很少,最多不超过10%,一般只有 ...
- C# listview 拖动节点
/// <summary> /// 当拖动某项时触发 /// </summary> /// <param name="sender"></ ...
- 基于python的flask的应用实例注意事项
1.所有的html文件均保存在templates文件夹中 2.运行网页时python manage.py runserver
- 解读Python发送邮件
解读Python发送邮件 Python发送邮件需要smtplib和email两个模块.也正是由于我们在实际工作中可以导入这些模块,才使得处理工作中的任务变得更加的简单.今天,就来好好学习一下使用Pyt ...
- 2012年 蓝桥杯预赛 java 本科 题目
2012年 蓝桥杯预赛 java 本科 考生须知: l 考试时间为4小时. l 参赛选手切勿修改机器自动生成的[考生文件夹]的名称或删除任何自动生成的文件或目录,否则会干扰考试系统正确采集您的解答 ...
- 初识zookeeper(一)之zookeeper的安装及配置
1.简要介绍 zookeeper是一个分布式的应用程序协调服务,是Hadoop和Hbase的重要组件,是一个树型的目录服务,支持变更推送.除此还可以用作dubbo服务的注册中心. 2.安装 2.1 下 ...
- FZU 1608 Huge Mission(线段树)
Problem 1608 Huge Mission Time Limit: 1000 mSec Memory Limit : 32768 KB Problem Description Oaiei ...
- LeetCode题目分类
利用堆栈:http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/http://oj.leetcode.com/problem ...
- Virtual Box上安装CentOS7
问题1:安装完没有桌面系统(Gnome或KDE)解答:安装的时候,软件选择为最小安装",更改该选择 问题2:开机提示Initial setup of CentOS Linux 7 (core ...