iOS 数据持久化(归档与反归档)
2014-09-10 19:55
232 查看
IOS 数据持久化(归档与反归档)
数据持久化,实际上就是将数据存放到网络或者硬盘上,这里是存储到本地的硬盘上,应用程序的本地硬盘是沙盒,沙盒实际上就是一个文件夹,它下面有4个文件夹。分别是Documents,Library,APP包和tmp文件夹
Documents里面主要是存储用户长期使用的文件,
Library里面又有Caches和Preferences文件夹,
(1)Caches里面存放的是临时的文件,缓存。
(2)Preferences里面存放的是偏好设置。比如:程序是否是第一次启动
tmp里面也是临时的文件,不过和Caches还有区别,
APP包里面是编译后的一些文件,包不能修改。
一.首先创建一个Person类
.h文件
#import
<Foundation/Foundation.h>
//如果要对一个类的对象实现归档操作,必须让该类服从NSCoding协议
@interface Person :NSObject<NSCoding>
@property (nonatomic,copy)
NSString *name;
@property (nonatomic,copy)
NSString *gender;
@property (nonatomic,assign)
NSInteger age;
- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age;
@end
.m文件
#import"Person.h"
@implementation Person
- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age
{
self = [superinit];
if (self) {
//1.当对象为字符串,
数组, 字典, 集合时,
属性的语义特性声明为copy
//2.定义完属性再给实例变量赋值时,
要使用setter方法
//3.一定要注意属性的内存管理
self.name = name;
self.gender = gender;
self.age = age;
}
return self;
}
//当对一个对象归档时,会调用对象的该方法,为该对象自己的实力变量进行归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoderencodeObject:_nameforKey:@"name"];
[aCoderencodeObject:_genderforKey:@"gender"];
[aCoderencodeObject:@(_age)forKey:@"age"];
}
//当对一个对象反归档时,会调用对象的该方法,为该对象的实例变量进行反归档
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [superinit];
if (self) {
self.name = [aDecoder
decodeObjectForKey:@"name"];
self.gender = [aDecoder
decodeObjectForKey:@"gender"];
self.age = [[aDecoderdecodeObjectForKey:@"age"]integerValue];
}
return self;
}
- (void)dealloc
{
self.name =nil;
self.gender =nil;
[superdealloc];
}
@end
二:主程序中的归档与反归档(.m文件)
这里面为了易于理解,创建TextFiled 以及其他控件一起写出来了
#import
"SecondViewController.h"
#import
"Person.h"
@interfaceSecondViewController ()<UITextFieldDelegate>
@end
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNil
bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
returnself;
}
- (void)viewDidLoad
{
[superviewDidLoad];
[selfcustomizeNavigationControl];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColorwhiteColor];
//创建视图控件
//textFile1
UITextField *firstFiled = [[UITextFieldalloc]
initWithFrame:CGRectMake(30,94,
260, 30)];
firstFiled.delegate =self;
firstFiled.tag =100;
firstFiled.placeholder =@"请输入内容";
firstFiled.autocorrectionType =UITextAutocorrectionTypeNo;
firstFiled.borderStyle =UITextBorderStyleRoundedRect;
[self.viewaddSubview:firstFiled];
[firstFiled
release];
//textFile2
UITextField *secondFiled = [[UITextFieldalloc]
initWithFrame:CGRectMake(30,154,
260, 30)];
secondFiled.delegate =self;
secondFiled.tag =101;
secondFiled.autocorrectionType =UITextAutocorrectionTypeNo;
secondFiled.placeholder =@"显示上一个输入框的内容";
secondFiled.borderStyle =UITextBorderStyleRoundedRect;
[self.viewaddSubview:secondFiled];
[secondFiled
release];
//writeButton
UIButton *pigeonholeButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
pigeonholeButton.frame =CGRectMake(30,
214,100, 30);
[pigeonholeButton
setTitle:@"归档"forState:UIControlStateNormal];
[pigeonholeButton
setTitleColor:[UIColorblueColor]
forState:UIControlStateNormal];
[pigeonholeButton
addTarget:self
action:@selector(pigeonholeClick:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:pigeonholeButton];
//readButton
UIButton *againstPigeonholeButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
againstPigeonholeButton.frame =CGRectMake(190,
214, 100, 30);
[againstPigeonholeButtonsetTitle:@"反归档"forState:UIControlStateNormal];
[againstPigeonholeButtonsetTitleColor:[UIColorblueColor]
forState:UIControlStateNormal];
[againstPigeonholeButton
addTarget:self action:@selector(againstPigeonholeClick:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:againstPigeonholeButton];
}
//归档
- (void)pigeonholeClick:(UIButton *)pigeonholeBtn
{
//1.获取输入框的内容
UITextField *tf1 = (UITextField *)[self.viewviewWithTag:100];
UITextField *tf2 = (UITextField *)[self.viewviewWithTag:101];
//封装成Person对象
Person *per = [[Personalloc]
initWithName:tf1.textgender:tf2.text
age:18];
//一.创建归档对象
NSMutableData *data = [NSMutableDatadata];
NSKeyedArchiver *archiver = [[NSKeyedArchiveralloc]
initForWritingWithMutableData:data];
//二.归档
[archiver
encodeObject:perforKey:@"Tsummer"];
//三.结束归档当结束归档之后再归档无效.
[archiver
finishEncoding];
[per
release];
[archiver
release];
//四.data写入文件
[data
writeToFile:[selfgetFilePath]
atomically:YES];
}
//反归档
- (void)againstPigeonholeClick:(UIButton *)againstPigeonholeBtn
{
//1.根据文件路径初始化NSMutableData对象
NSMutableData *mData = [NSMutableDatadataWithContentsOfFile:[selfgetFilePath]];
//2.创建一个反归档对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiveralloc]
initForReadingWithData:mData];
//3.反归档
Person *per = [unarchiverdecodeObjectForKey:@"Tsummer"];
//4.结束反归档
[unarchiver
finishDecoding];
[unarchiver
release];
UITextField *tf1 = (UITextField *)[self.viewviewWithTag:100];
tf1.text = per.gender;
UITextField *tf2 = (UITextField *)[self.viewviewWithTag:101];
tf2.text = per.name;
NSLog(@"反归档");
}
//获取文件路径
- (NSString *)getFilePath
{
//1.先获得Documents文件夹的路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) firstObject];
//(2)拼接上文件路径
NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"Tsummer.txt"];
NSLog(@"%@", newFilePath);
return newFilePath;
}
//定制navigationControl
- (void)customizeNavigationControl
{
self.navigationItem.title =@"归档与反归档";
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField
resignFirstResponder];
returnYES;
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
数据持久化,实际上就是将数据存放到网络或者硬盘上,这里是存储到本地的硬盘上,应用程序的本地硬盘是沙盒,沙盒实际上就是一个文件夹,它下面有4个文件夹。分别是Documents,Library,APP包和tmp文件夹
Documents里面主要是存储用户长期使用的文件,
Library里面又有Caches和Preferences文件夹,
(1)Caches里面存放的是临时的文件,缓存。
(2)Preferences里面存放的是偏好设置。比如:程序是否是第一次启动
tmp里面也是临时的文件,不过和Caches还有区别,
APP包里面是编译后的一些文件,包不能修改。
一.首先创建一个Person类
.h文件
#import
<Foundation/Foundation.h>
//如果要对一个类的对象实现归档操作,必须让该类服从NSCoding协议
@interface Person :NSObject<NSCoding>
@property (nonatomic,copy)
NSString *name;
@property (nonatomic,copy)
NSString *gender;
@property (nonatomic,assign)
NSInteger age;
- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age;
@end
.m文件
#import"Person.h"
@implementation Person
- (id)initWithName:(NSString *)name gender:(NSString *)gender age:(NSInteger)age
{
self = [superinit];
if (self) {
//1.当对象为字符串,
数组, 字典, 集合时,
属性的语义特性声明为copy
//2.定义完属性再给实例变量赋值时,
要使用setter方法
//3.一定要注意属性的内存管理
self.name = name;
self.gender = gender;
self.age = age;
}
return self;
}
//当对一个对象归档时,会调用对象的该方法,为该对象自己的实力变量进行归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoderencodeObject:_nameforKey:@"name"];
[aCoderencodeObject:_genderforKey:@"gender"];
[aCoderencodeObject:@(_age)forKey:@"age"];
}
//当对一个对象反归档时,会调用对象的该方法,为该对象的实例变量进行反归档
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [superinit];
if (self) {
self.name = [aDecoder
decodeObjectForKey:@"name"];
self.gender = [aDecoder
decodeObjectForKey:@"gender"];
self.age = [[aDecoderdecodeObjectForKey:@"age"]integerValue];
}
return self;
}
- (void)dealloc
{
self.name =nil;
self.gender =nil;
[superdealloc];
}
@end
二:主程序中的归档与反归档(.m文件)
这里面为了易于理解,创建TextFiled 以及其他控件一起写出来了
#import
"SecondViewController.h"
#import
"Person.h"
@interfaceSecondViewController ()<UITextFieldDelegate>
@end
@implementation SecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [superinitWithNibName:nibNameOrNil
bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
returnself;
}
- (void)viewDidLoad
{
[superviewDidLoad];
[selfcustomizeNavigationControl];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColorwhiteColor];
//创建视图控件
//textFile1
UITextField *firstFiled = [[UITextFieldalloc]
initWithFrame:CGRectMake(30,94,
260, 30)];
firstFiled.delegate =self;
firstFiled.tag =100;
firstFiled.placeholder =@"请输入内容";
firstFiled.autocorrectionType =UITextAutocorrectionTypeNo;
firstFiled.borderStyle =UITextBorderStyleRoundedRect;
[self.viewaddSubview:firstFiled];
[firstFiled
release];
//textFile2
UITextField *secondFiled = [[UITextFieldalloc]
initWithFrame:CGRectMake(30,154,
260, 30)];
secondFiled.delegate =self;
secondFiled.tag =101;
secondFiled.autocorrectionType =UITextAutocorrectionTypeNo;
secondFiled.placeholder =@"显示上一个输入框的内容";
secondFiled.borderStyle =UITextBorderStyleRoundedRect;
[self.viewaddSubview:secondFiled];
[secondFiled
release];
//writeButton
UIButton *pigeonholeButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
pigeonholeButton.frame =CGRectMake(30,
214,100, 30);
[pigeonholeButton
setTitle:@"归档"forState:UIControlStateNormal];
[pigeonholeButton
setTitleColor:[UIColorblueColor]
forState:UIControlStateNormal];
[pigeonholeButton
addTarget:self
action:@selector(pigeonholeClick:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:pigeonholeButton];
//readButton
UIButton *againstPigeonholeButton = [UIButtonbuttonWithType:UIButtonTypeCustom];
againstPigeonholeButton.frame =CGRectMake(190,
214, 100, 30);
[againstPigeonholeButtonsetTitle:@"反归档"forState:UIControlStateNormal];
[againstPigeonholeButtonsetTitleColor:[UIColorblueColor]
forState:UIControlStateNormal];
[againstPigeonholeButton
addTarget:self action:@selector(againstPigeonholeClick:)forControlEvents:UIControlEventTouchUpInside];
[self.viewaddSubview:againstPigeonholeButton];
}
//归档
- (void)pigeonholeClick:(UIButton *)pigeonholeBtn
{
//1.获取输入框的内容
UITextField *tf1 = (UITextField *)[self.viewviewWithTag:100];
UITextField *tf2 = (UITextField *)[self.viewviewWithTag:101];
//封装成Person对象
Person *per = [[Personalloc]
initWithName:tf1.textgender:tf2.text
age:18];
//一.创建归档对象
NSMutableData *data = [NSMutableDatadata];
NSKeyedArchiver *archiver = [[NSKeyedArchiveralloc]
initForWritingWithMutableData:data];
//二.归档
[archiver
encodeObject:perforKey:@"Tsummer"];
//三.结束归档当结束归档之后再归档无效.
[archiver
finishEncoding];
[per
release];
[archiver
release];
//四.data写入文件
[data
writeToFile:[selfgetFilePath]
atomically:YES];
}
//反归档
- (void)againstPigeonholeClick:(UIButton *)againstPigeonholeBtn
{
//1.根据文件路径初始化NSMutableData对象
NSMutableData *mData = [NSMutableDatadataWithContentsOfFile:[selfgetFilePath]];
//2.创建一个反归档对象
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiveralloc]
initForReadingWithData:mData];
//3.反归档
Person *per = [unarchiverdecodeObjectForKey:@"Tsummer"];
//4.结束反归档
[unarchiver
finishDecoding];
[unarchiver
release];
UITextField *tf1 = (UITextField *)[self.viewviewWithTag:100];
tf1.text = per.gender;
UITextField *tf2 = (UITextField *)[self.viewviewWithTag:101];
tf2.text = per.name;
NSLog(@"反归档");
}
//获取文件路径
- (NSString *)getFilePath
{
//1.先获得Documents文件夹的路径
NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES) firstObject];
//(2)拼接上文件路径
NSString *newFilePath = [documentsPath stringByAppendingPathComponent:@"Tsummer.txt"];
NSLog(@"%@", newFilePath);
return newFilePath;
}
//定制navigationControl
- (void)customizeNavigationControl
{
self.navigationItem.title =@"归档与反归档";
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField
resignFirstResponder];
returnYES;
}
- (void)didReceiveMemoryWarning
{
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
相关文章推荐
- IOS之数据持久化(归档与反归档)
- iOS 数据持久化(1):属性列表与对象归档
- IOS开发-数据持久化(一)【文本文件+二进制归档】
- iOS数据持久化 归档 plist文件
- 归档与反归档(ios数据持久化)
- iOS-数据持久化存储(归档)
- IOS 数据持久化(三)—— 归档与解档
- 【IOS-Swift】实战笔记——数据持久化之归档NSKeyedArchiver
- iOS数据持久化存储之归档NSKeyedArchiver
- iOS开发之归档
- 【iOS知识学习】_数据持久化
- IOS 数据持久化
- ios数据存储之--对模型对象归档(NSKeyedArchiver、NSKeyedUnarchiver)
- IOS随笔——归档和解归档
- iOS 归档持久化数据
- iOS学习笔记05—数据持久化
- ios实现 本地存储 数据持久化
- ios开发中归档的使用
- 文件数据IOS学习:ios中的数据持久化初级(文件、xml、json、sqlite、CoreData)
- IOS之数据持久化