IOS 归档 即序列化与反序列化

小弟很久没有更新了 最近在往IOS上靠

IOS中的归档  即是我们所知道的序列化和反序列化

我们可以用plist来存储比较简单的数据类型 但是如果我想把自己定义的类型进行持久化呢?

这就要用到序列化了 下面贴代码

先是自定义一个自己的类  需要继承 NSCoding  接口

-------------------------------------//我是分隔线//-----------------------------------------

#import <Foundation/Foundation.h>

@interface FourLines : NSObject <NSCoding,NSCopying> {

}
@property (nonatomic,retain) NSString *field1;
@property (nonatomic,retain) NSString *field2;
@property (nonatomic,retain) NSString *field3;
@property (nonatomic,retain) NSString *field4;

@end

#import "FourLines.h"
#define kField1Key @"Field1"
#define kField2Key @"Field2"
#define kField3Key @"Field3"
#define kField4Key @"Field4"

@implementation FourLines

@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;

- (void) encodeWithCoder:(NSCoder *)aCoder{
 [aCoder encodeObject:field1 forKey:kField1Key];
 [aCoder encodeObject:field2 forKey:kField2Key];
 [aCoder encodeObject:field3 forKey:kField3Key];
 [aCoder encodeObject:field4 forKey:kField4Key];
}

- (id)initWithCoder:(NSCoder *)aDecoder{
 if (self = [super init]) {
  field1 = [[aDecoder decodeObjectForKey:kField1Key] retain];
  field2 = [[aDecoder decodeObjectForKey:kField2Key] retain];
  field3 = [[aDecoder decodeObjectForKey:kField3Key] retain];
  field4 = [[aDecoder decodeObjectForKey:kField4Key] retain];
 }
 return self;
}

- (id)copyWithZone:(NSZone *)zone{
 FourLines *copy = [[[self class] allocWithZone:zone] init];
 copy.field1 = [[self.field1 copyWithZone:zone] autorelease];
 copy.field2 = [[self.field2 copyWithZone:zone] autorelease];
 copy.field3 = [[self.field3 copyWithZone:zone] autorelease];
 copy.field4 = [[self.field4 copyWithZone:zone] autorelease];
 return copy;
}

- (void)dealloc{
 [field1 release];
 [field2 release];
 [field3 release];
 [field4 release];
 [super dealloc];
}

@end

下面是一个controller 来实现如何持久化自定义类

#import <UIKit/UIKit.h>

//#define kFilename @"data.plist"
#define kFilename @"archive"
#define kDataKey @"Data"
 //define kFilename @"dataarchiive.plist"
 //#define kDataKey @"Data"
 //#define kFilename @"data.sqlite3"

@interface PersistenceViewController : UIViewController {

}
@property (nonatomic,retain) IBOutlet UITextField *field1;
@property (nonatomic,retain) IBOutlet UITextField *field2;
@property (nonatomic,retain) IBOutlet UITextField *field3;
@property (nonatomic,retain) IBOutlet UITextField *field4;

- (NSString *)dataFilePath;
- (void)applicationWillResignActive:(NSNotification *)notification;

@end

#import "PersistenceViewController.h"
#import "FourLines.h"

@implementation PersistenceViewController

@synthesize field1;
@synthesize field2;
@synthesize field3;
@synthesize field4;

- (NSString *)dataFilePath{
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
 NSLog(@"Document Path:%@",documentsDirectory);
 return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
 NSString *filePath = [self dataFilePath];
 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
  /*
  NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath];
  field1.text = [array objectAtIndex:0];
  field2.text = [array objectAtIndex:1];
  field3.text = [array objectAtIndex:2];
  field4.text = [array objectAtIndex:3];
  [array release];
  */
  
   //encoding
  NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];
  NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
  
  FourLines *fourLines = [unarchiver decodeObjectForKey:kDataKey];
  [unarchiver finishDecoding];
  
  field1.text = fourLines.field1;
  field2.text = fourLines.field2;
  field3.text = fourLines.field3;
  field4.text = fourLines.field4;
  
  [unarchiver release];
  [data release];
 }
 
 UIApplication *app = [UIApplication sharedApplication];
 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    [super viewDidLoad];
}

- (void) applicationWillResignActive:(NSNotification *)notification{
 /*
 NSMutableArray *array = [[NSMutableArray alloc] init];
 [array addObject:field1.text];
 [array addObject:field2.text];
 [array addObject:field3.text];
 [array addObject:field4.text];
 [array writeToFile:[self dataFilePath] atomically:YES];
 */
 FourLines *fourLine = [[FourLines alloc] init];
 fourLine.field1 = field1.text;
 fourLine.field2 = field2.text;
 fourLine.field3 = field3.text;
 fourLine.field4 = field4.text;
 
 NSMutableData *data = [[NSMutableData alloc] init];
 NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
 [archiver encodeObject:fourLine forKey:kDataKey];
 [archiver finishEncoding];
 [data writeToFile:[self dataFilePath] atomically:YES];
 [fourLine release];
 [data release];
 [archiver release];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
 // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

- (void)dealloc {
 [field1 release];
 [field2 release];
 [field3 release];
 [field4 release];
    [super dealloc];
}

@end

希望能对您有帮助  下次分享如何使用嵌入式数据库  sqlite3

posted on 2012-03-09 14:06 吃螺丝 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/Kiros/archive/2012/03/09/2387532.html

IOS 归档 即序列化与反序列化相关推荐

  1. ios序列化与反序列化,本地化

    2019独角兽企业重金招聘Python工程师标准>>> 你是用什么方法来持久保存数据的?这是在几乎每一次关于iOS技术的交流或讨论都会被提到的问题,而且大家对这个问题的热情持续高涨. ...

  2. iOS 各种系统文件目录 临时,缓存,document,lib,归档,序列化

    Java代码   /** 1:Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录 2:tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在 ...

  3. ios php 序列化,PHP常见的序列化与反序列化操作实例分析

    本文实例讲述了PHP常见的序列化与反序列化操作.分享给大家供大家参考,具体如下: 1.概念 serialize() 把变量和它们的值编码成文本形式 unserialize() 恢复原先变量 2.序列化 ...

  4. iOS序列化与反序列化

    1到底这个序列化有啥作用? 面向对象的程序在运行的时候会创建一个复杂的对象图,经常要以二进制的方法序列化这个对象图,这个过程叫做Archiving. 二进制流可以通过网络或写入文件中(来源于某教材的一 ...

  5. iOS 序列化与反序列化

    开篇 1到底这个序列化有啥作用? 面向对象的程序在运行的时候会创建一个复杂的对象图,经常要以二进制的方法序列化这个对象图,这个过程叫做Archiving. 二进制流可以通过网络或写入文件中(来源于某教 ...

  6. c语言 序列化,序列化和反序列化

    定义以及相关概念 互联网的产生带来了机器间通讯的需求,而互联通讯的双方需要采用约定的协议,序列化和反序列化属于通讯协议的一部分.通讯协议往往采用分层模型,不同模型每层的功能定义以及颗粒度不同,例如:T ...

  7. JSON数据序列化与反序列化实战

    一.关于JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.是一种文件规范,绝大多数的编程语言均可以轻松读写.当然python也不 ...

  8. YUDBModel【绿色插件】-对象序列化、反序列化、对象一键增删改查

    2019独角兽企业重金招聘Python工程师标准>>> 一.YUDBModel 介绍 架构: 使用runtime和Sqlite实现NSObject扩展类YUDBModel,直接实现( ...

  9. 【Protocol Buffer】Protocol Buffer入门教程(四):序列化和反序列化

    00. 目录 文章目录 00. 目录 01. 数组的序列化和反序列化 02. 字符串序列化和反序列化 03. 文件描述符序列化和反序列化 04. C++ Stream序列化和反序列化 05. 附录 0 ...

最新文章

  1. BOOKS STORE OPENCART 自适应主题模板 ABC-0093
  2. ANSYS配合时如何选择重合面(打开爆炸视图)
  3. 弹出窗口显示输出内容_前端加油站(3)-JavaScript 输出
  4. SQL日期时间和字符串函数
  5. 内存溢出_JVM|03内存溢出实战
  6. Android-JNI开发系列《七》补充jni与java的数据类型的对应关系和数据类型描述符
  7. 【分论坛第一期大剧透】开源技术与新IT基础设施联袂共舞
  8. php tableau,Tableau函数
  9. 【Makefile】简单的Makefile编写
  10. 公司年会要求搞一个抽奖程序,及时安排一波
  11. 计算机时钟同步的原理,华为以太网时钟同步原理介绍(二)
  12. python爬虫之淘宝秒抢软件
  13. 磨刀不误砍柴工(一)-高效的第一步
  14. php源码dede,php网站管理系统 DedeCMS v5.7 SP2 UTF8 20180109正式版
  15. 连上WiFi就能打电话?“手机营业厅”中的神奇功能火了
  16. 视频教程-jQuery交互式前端开发(第一季):初体验/选择器/事件绑定-jQuery
  17. HTML绘制齿轮,使用css3制作齿轮loading动画效果
  18. 华为设备STP和RSTP配置命令
  19. 深入了解Socks5代理IP和网络安全
  20. execve系统调用_系统调用execve的入口sys_execve() | 学步园

热门文章

  1. Linux下7z工具安装
  2. Android RecyclerView批量更新notifyItemRangeChanged
  3. linux rsync配置文件参数详解
  4. struts2 action 返回类型分析
  5. nginx rwrite及增加不记录特定状态日志nginx模块
  6. 23种设计模式(3):抽象工厂模式
  7. rhcsa第二天笔记
  8. xcode 4,2 for Mac 10.6.8
  9. 留存光明延续大爱 80后父母捐病儿角膜感动冰城
  10. struts2实现文件上传