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的创建,数据写入与读取 Documents:应用将数据存储在Documents中,但基于NSuserDefaults的首选项设置除外Library:基于NSUserDefaults的 ...
- 蜗牛爱课- iOS中plist的创建,数据写入与读取
iOS中plist的创建,数据写入与读取功能创建一个test.plist文件-(void)triggerStorage{ NSArray *paths=NSSearchPathForDirect ...
- UWP入门(十)--创建、写入和读取文件
原文:UWP入门(十)--创建.写入和读取文件 核心的 API github代码 StorageFolder 类 StorageFile 类 FileIO 类 使用 StorageFile 对象读取和 ...
- 在C#程序中,创建、写入、读取XML文件的方法
一.在C#程序中,创建.写入.读取XML文件的方法 1.创建和读取XML文件的方法,Values为需要写入的值 private void WriteXML(string Values) { //保存的 ...
- iOS中偏好设置的创建,数据写入与读取
NSUserDefaults与NSDictinary? 应用通过NSUserDefaults用键值对的方式来读取和保存偏好设置数据,与通过键从NSDictionary对象中获取数据一样,不同之处在于N ...
- iOS——偏好设置的创建,数据写入与读取
NSUserDefaults与NSDictinary? 应用通过NSUserDefaults用键值对的方式来读取和保存偏好设置数据,与通过键从NSDictionary对象中获取数据一样,不同之处在于N ...
- js创建、写入、读取文件(转)
下面是对此知识的系统介绍(转自互联网): Javascript 是网页制作中离不开的脚本语言,依靠它,一个网页的内容才生动活泼.富有朝气.但也许你还没有发现并应用它的一些更高级的功能吧?比如,对文件和 ...
- iOS中归档对象的创建,数据写入与读取
归档(archiving)是指另一种形式的序列化,但它是任何对象都可以实现的更常规的模型.专门编写用于保存数据的任何模型对象都应该支持归档.比属性列表多了很良好的伸缩性,因为无论添加多少对象,将这些对 ...
随机推荐
- 使用phpstudy搭建的外网网站 运行很慢 解决办法
将连接数据库的配置文件 localhost 修改为127.0.0.1 PHP5.3以上,如果是链接localhost,会检测是IPV4还是IPV6,所以会比较慢.解决办法是:链接数据的时候,不要填写 ...
- .gitignore文件不起作用,怎么处理?
遇到这么个场景,项目之前没有.gitignore文件,新建的.gitignore文件中已经标明忽略的文件目录下的文件,但是git push上去忽略的文件还是在push的目录中.查阅资料了解到 在git ...
- 第81题:搜索旋转排序数组II
一. 问题描述 假设按照升序排序的数组在预先未知的某个点上进行了旋转. ( 例如,数组 [0,0,1,2,2,5,6] 可能变为 [2,5,6,0,0,1,2] ). 编写一个函数来判断给定的目标值是 ...
- 27-SQLServer系统扩展存储过程
一.注意点 1.在SQLServer中,有些系统扩展存储过程,是有风险,需要取消public角色的执行权限. 2.从SQLServer2005开始就不能通过sp_dropextendedproc 删除 ...
- mysql group_concat长度限制
group_concat函数有长度限制 查找当前数据库长度 show variables like 'group_concat_max_len' 设置当前session的group_concat长度, ...
- 2019HDU多校Path——最短路最小割
题目 给出一个 $n$ 个顶点 $m$ 条边的图,要求阻塞一些边,使得从 $1$ 到 $n$ 的最短路变长,求阻塞的边长度和的最小值,不必保证阻塞后可达. 分析 很显然,要阻塞的边肯定在最短路图上,先 ...
- 冒泡排序之javascript
冒泡排序是一种简单的排序算法.它重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来.走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成.这个算法的名字 ...
- PHP mysqli_connect_error() 函数
返回上一次连接错误的错误描述: <?php $con=mysqli_connect("localhost","wrong_user","my_p ...
- Flutter布局----弹性布局 (Flex)
弹性布局(Flex) 弹性布局允许子组件按照一定比例来分配父容器空间.弹性布局的概念在其它UI系统中也都存在,如H5中的弹性盒子布局,Android中的FlexboxLayout等.Flutter中的 ...
- laotech老师唠科mac 深入浅出MAC OS X
laotech老师唠科mac 深入浅出MAC OS X http://study.163.com/plan/planLearn.htm?id=1637004#/learn/resVideo?lesso ...