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

转载请注明出处,原文网址:http://blog.csdn.net/m_changgong/article/details/8284135 作者:张燕广

实现的功能:1)演示使用归档持久化数据。

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

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


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类的实例)。

需要源码的网友请留言哦


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值