`

iPhone开发数据持久化总结之第3篇—归档(NSKeyedArchiver、NSKeyedUnarchiver) .

    博客分类:
  • ios
ios 
阅读更多
实现的功能:1)演示使用归档持久化数据。

关键词:数据持久化 归档  NSKeyedArchiver NSKeyedUnarchiver

1、将上一篇iPhone开发数据持久化总结之第2篇属性文件(.plist)的工程拷贝一份,名称修改为Persistence-archiver,工程结构如下:
[img]

[/img]



2、添加Person.h类,如下:

Person.h:

#import <Foundation/Foundation.h>

@interface Person : NSObject<NSCoding,NSCopying> 
@property(nonatomic,retain)NSString *name;
@property(nonatomic,retain)NSString *gender;
@property(nonatomic,retain)NSString *age;
@property(nonatomic,retain)NSString *education;
@end




Person.m:
#import "Person.h"
#define kNameKey        @"name"
#define kGenderKey      @"gender"
#define kAgeKey         @"age"
#define kEducationKey   @"education"
@implementation Person
@synthesize name,gender,age,education;

#pragma mark -
#pragma mark NSCoding
-(void)encodeWithCoder:(NSCoder *)aCoder{//编码
    [aCoder encodeObject:name forKey:kNameKey];
    [aCoder encodeObject:gender forKey:kGenderKey];
    [aCoder encodeObject:age forKey:kAgeKey];
    [aCoder encodeObject:education forKey:kEducationKey];
}

-(id)initWithCoder:(NSCoder *)aDecoder{//解码
    if(self == [super init]){
        name = [[aDecoder decodeObjectForKey:kNameKey]retain];
        gender = [[aDecoder decodeObjectForKey:kGenderKey]retain];
        age = [[aDecoder decodeObjectForKey:kAgeKey]retain];
        education = [[aDecoder decodeObjectForKey:kEducationKey]retain];
    }
    return self;
}

#pragma mark -
#pragma mark NSCopying
-(id)copyWithZone:(NSZone *)zone{
    Person *person = [[[self class]allocWithZone:zone]init];
    person.name = [[self.name copyWithZone:zone]autorelease];
    person.gender = [[self.gender copyWithZone:zone]autorelease];
    person.name = [[self.name copyWithZone:zone]autorelease];
    person.name = [[self.name copyWithZone:zone]autorelease];
    return person;
}

@end





3、接下来主要修改ViewController
ViewController.h,主要是修改了宏,如下:

//#define kFileName @"data.plist"
#define kFileName @"archive"
#define kDataKey @"Data"

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
@property(nonatomic,retain)IBOutlet UITextField *name;
@property(nonatomic,retain)IBOutlet UITextField *gender;
@property(nonatomic,retain)IBOutlet UITextField *age;
@property(nonatomic,retain)IBOutlet UITextField *education;

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

@end


主要修改了ViewController.m,如下:
#import "ViewController.h"
#import "Person.h"

@implementation ViewController
@synthesize name,gender,age,education;

-(NSString *)dataFilePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFileName];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
	// Do any additional setup after loading the view, typically from a nib.
    NSString *filePath = [self dataFilePath];
    NSLog(@"filePath=%@",filePath);
    
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){
        //属性列表
        /*
        NSArray *array = [[NSArray alloc]initWithContentsOfFile:filePath];
        name.text = [array objectAtIndex:0];
        gender.text = [array objectAtIndex:1];
        age.text = [array objectAtIndex:2];
        education.text = [array objectAtIndex:3];
        
        [array release];*/
        
        NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[self dataFilePath]];
        NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
        Person *person = [unarchiver decodeObjectForKey:kDataKey];
        [unarchiver finishDecoding];
        
        name.text = person.name;
        gender.text = person.gender;
        age.text = person.age;
        education.text = person.education;
        
        [unarchiver release];
        [data release];
    }
    
    UIApplication *app = [UIApplication sharedApplication];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
    
    [super viewDidLoad];
}

-(void)applicationWillResignActive:(NSNotification *)nofication{
    
    //属性列表
    /*
    NSMutableArray *array = [[NSMutableArray alloc]init];
    [array addObject:name.text];
    [array addObject:gender.text];
    [array addObject:age.text];
    [array addObject:education.text];
    [array writeToFile:[self dataFilePath] atomically:YES];
    [array release];*/
    
    Person *person = [[Person alloc]init];
    person.name = name.text;
    person.gender = gender.text;
    person.age = age.text;
    person.education = education.text;
    
    NSMutableData *data = [[NSMutableData alloc]init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    [archiver encodeObject:person forKey:kDataKey];
    [archiver finishEncoding];
    
    [data writeToFile:[self dataFilePath] atomically:YES];
    [person release];
    [archiver release];
    [data release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.name = nil;
    self.gender = nil;
    self.age = nil;
    self.education = nil;
}

-(void)dealloc{
    [name release];
    [gender release];
    [age release];
    [education release];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end







4、通过iPhone开发【二十】数据持久化总结之第1篇NSUserDefaults 可以知道保存数据archive文件的存储位置是:
/Users/duobianxing/Library/Application Support/iPhone Simulator/5.0/Applications/F694104D-894D-4230-A01B-C62066B3DEC8/Documents




5、总结:

与属性列表相比,归档可以写入复杂的对象(Person类的实例)。



  • 大小: 35.4 KB
分享到:
评论

相关推荐

    iphone 数据持久化的三个实例

    本文将通过三个具体的实例深入探讨iPhone上实现数据持久化的三种方法:属性列表、对象归档和SQLite3数据库。 首先,我们来看**属性列表(Property List)**的使用。属性列表是iOS中一种简单且常用的数据存储方式,...

    iphoe通过对象归档实现数据持久化

    在iOS开发中,数据持久化是一项关键技能,它允许应用程序保存数据并在后续的使用中恢复这些数据,即使应用被关闭或设备重启。本教程聚焦于iPhone应用如何利用对象归档来实现数据持久化。对象归档是Objective-C中一种...

    读写数据-数据归档源码

    本资料提供的“读写数据-数据归档源码”是关于如何在iOS环境中进行数据持久化的实例,它涵盖了两个关键概念:读取数据和数据归档。接下来,我们将深入探讨这两个知识点。 一、读取数据 在iOS应用中,数据读取通常...

    深入理解iPhone数据持久化

    iPhone中的数据持久化方法主要包括属性列表(Property List)、对象归档(Object Archiving)、嵌入式数据库(SQLite3)以及其他一些方法。 首先,属性列表是处理简单数据(如字符串、数组和字典等)最直接的方法,...

    Iphone 序列化与反序列化,队列的实例

    在iOS开发中,序列化和反序列化是两个重要的概念,它们主要用于数据持久化和传输。序列化是指将对象转换为可存储或可传输的格式,如JSON、XML或二进制,而反序列化则是将这些格式的数据恢复为原始的对象形式。在...

    【Foundation Framework Reference】[PDF] [iPhone/iPad/iOS]

    同时,框架中的`NSKeyedArchiver`和`NSKeyedUnarchiver`类支持对象的归档和解归档,使得对象可以被序列化并保存到文件中,或者从文件中反序列化恢复出来,这对于数据持久化非常关键。 ### 网络通信 对于网络通信...

    IOS有用的Demo

    这些示例代码可以帮助开发者深入理解并掌握iOS应用开发的核心概念,尤其是针对界面展示、数据持久化以及编码解码等方面。下面我们将逐一解析这些Demo所涉及的知识点。 1. **09 Nav**: 这个Demo可能涉及到导航控制器...

    【Dealing with Data, User Defaults, SQLite, Web Services】[PDF] [iPhone/iPad/iOS]

    归档是另一种数据持久化策略,主要用于对象的序列化和反序列化。当需要将自定义对象保存到文件系统或通过网络传输时,归档是一种有效的方式。Objective-C和Swift均支持归档机制,可以通过`NSKeyedArchiver`和`...

    SDK与Objective-C 2.0.docx

    总之,理解iPhone OS的架构和SDK工具,掌握Objective-C 2.0的内存管理和容器使用,以及有效的通信和数据持久化技术,是成功开发iPhone应用程序的关键步骤。在实际开发中,这些知识点将贯穿于项目的各个阶段,从界面...

    iOS 读档写档删除添加

    在iOS应用开发中,"读档写档"(读取和保存数据)是常见的操作,尤其是在需要持久化用户数据或应用程序状态时。本篇将详细阐述iOS中的数据存储方法,包括如何读取、写入、删除和添加数据,并结合提供的`RecordTest.h`...

Global site tag (gtag.js) - Google Analytics