首页 > 代码库 > IOS开发-数据持久化(一)【文本文件+二进制归档】

IOS开发-数据持久化(一)【文本文件+二进制归档】

概要

    数据持久化分为不同的方式,本章主要简示了数据归档(一般而说的序列化)和写XML的文本文件方式。其中XML文本方式主要使用NSArray或者NSDictionary的writeToFile方法,而数据归档使用了NSKeyedArchiver/NSKeyedUnarchiver等实现数据的归档(序列化)。


结果展示


程序展示


数据化文件

      注意新版本的IOS模拟器的目录和以前的目录不在同一个地方,其中plist文件是XML文件,可打开直接查看,而archi是归档的二进制文件。


流程概要


1.新建工程,拖拉界面,完成程序除归档外的操作,具体操作:略

2.对于XML存储,将需要存储的数据放到字典或者数组中,然后调用WriteToFile把数据保存到文件,使用类方法initWithContentsOfFile读取存储的数据即可

3.数据归档化相对而言较复杂点,需要新建一个数据类,该类需要实现了NSCoding协议,然后实现编码和解码两个方法。

4.在需要数据存储的地方把需要的数据放到步骤3中的数据类的对象中,然后结合使用NSMutableData和NSKeyedArchiver实现数据归档。

5.略


主要代码

数据类

h文件
//
//  Staff.h
//  DataXMLArchiver
//
//  Created by God Lin on 14/12/9.
//  Copyright (c) 2014年 arbboter. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface Staff : NSObject <NSCoding>
{
    NSString* _nickName;
    NSString* _email;
    NSString* _phone;
    NSString* _sex;
    NSString* _position;
}

@property (nonatomic, retain) NSString* _nickName;
@property (nonatomic, retain) NSString* _email;
@property (nonatomic, retain) NSString* _phone;
@property (nonatomic, retain) NSString* _sex;
@property (nonatomic, retain) NSString* _position;
@end

m文件
//
//  Staff.m
//  DataXMLArchiver
//
//  Created by God Lin on 14/12/9.
//  Copyright (c) 2014年 arbboter. All rights reserved.
//

#import "Staff.h"

@implementation Staff

@synthesize _nickName;
@synthesize _email;
@synthesize _phone;
@synthesize _sex;
@synthesize _position;

#pragma NSCoding 实现序列化(归档)
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self._nickName forKey:@"nickName"];
    [aCoder encodeObject:self._email forKey:@"email"];
    [aCoder encodeObject:self._phone forKey:@"phone"];
    [aCoder encodeObject:self._sex forKey:@"sex"];
    [aCoder encodeObject:self._position forKey:@"position"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
    self._nickName = [aDecoder decodeObjectForKey:@"nickName"];
    self._email = [aDecoder decodeObjectForKey:@"email"];
    self._phone = [aDecoder decodeObjectForKey:@"phone"];
    self._sex = [aDecoder decodeObjectForKey:@"sex"];
    self._position = [aDecoder decodeObjectForKey:@"position"];
    return self;
}
@end


程序主体代码

h文件
//
//  ViewController.h
//  DataXMLArchiver
//
//  Created by God Lin on 14/12/9.
//  Copyright (c) 2014年 arbboter. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UITextField* _textNickName;
    IBOutlet UITextField* _textEmail;
    IBOutlet UITextField* _textPhone;
    IBOutlet UITextField* _textSex;
    IBOutlet UITextField* _textPosition;
}
@property (nonatomic, retain) UITextField* _textNickName;
@property (nonatomic, retain)UITextField* _textEmail;
@property (nonatomic, retain)UITextField* _textPhone;
@property (nonatomic, retain)UITextField* _textSex;
@property (nonatomic, retain)UITextField* _textPosition;

-(IBAction)onHideKeyboard:(id)sender;
-(IBAction)onXmlSave:(id)sender;
-(IBAction)onXmlLoad:(id)sender;
-(IBAction)onArchiverSave:(id)sender;
-(IBAction)onArchiverLoad:(id)sender;
@end

m文件
//
//  ViewController.m
//  DataXMLArchiver
//
//  Created by God Lin on 14/12/9.
//  Copyright (c) 2014年 arbboter. All rights reserved.
//

#import "ViewController.h"
#import "Staff.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize _textNickName;
@synthesize _textEmail;
@synthesize _textPhone;
@synthesize _textSex;
@synthesize _textPosition;


-(IBAction)onHideKeyboard:(id)sender
{
    [sender resignFirstResponder];
}
-(NSString*)getDocumentDir
{
    // 获取保存的文件名
    NSArray* arrayPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [arrayPath objectAtIndex:0];
}
-(void)textClear
{
    self._textNickName.text = @"";
    self._textEmail.text = @"";
    self._textPhone.text = @"";
    self._textSex.text = @"";
    self._textPosition.text = @"";
}

// XML文本保存数据,可使用数组字典等保存数据
-(IBAction)onXmlSave:(id)sender
{
    // 保存数据到字典
    NSMutableDictionary* dict = [[NSMutableDictionary alloc] init];
    [dict setObject:self._textNickName.text forKey:@"nickName"];
    [dict setObject:self._textEmail.text forKey:@"email"];
    [dict setObject:self._textPhone.text forKey:@"phone"];
    [dict setObject:self._textSex.text forKey:@"sex"];
    [dict setObject:self._textPosition.text forKey:@"position"];
    
    NSString* pathFile = [self getDocumentDir];
    pathFile = [pathFile stringByAppendingPathComponent:@"staff.plist"];
    
    // 数据写入文件
    [dict writeToFile:pathFile atomically:YES];
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Infomation" message:@"Save finished" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    // 使用ARC,自己不需要管理内存
    //[alert release];
    [self textClear];
}
-(IBAction)onXmlLoad:(id)sender
{
    // 获取保存的文件名
    NSString* pathFile = [self getDocumentDir];
    pathFile = [pathFile stringByAppendingPathComponent:@"staff.plist"];
    
    NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:pathFile];
    self._textNickName.text = [dict objectForKey:@"nickName"];
    self._textEmail.text = [dict objectForKey:@"email"];
    self._textPhone.text = [dict objectForKey:@"phone"];
    self._textSex.text = [dict objectForKey:@"sex"];
    self._textPosition.text = [dict objectForKey:@"position"];
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Infomation" message:@"Load finished" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}

// 归档化数据
-(IBAction)onArchiverSave:(id)sender
{
    Staff* staff = [[Staff alloc] init];
    staff._nickName = self._textNickName.text;
    staff._email = self._textEmail.text;
    staff._phone = self._textPhone.text;
    staff._sex = self._textSex.text;
    staff._position = self._textPosition.text;
    
    // 新建二进制内存(读写)
    NSMutableData* data = [[NSMutableData alloc] init];
    
    // 设置二进制内存数据内容(读写)
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:staff forKey:@"staff"];
    [archiver finishEncoding];
    
    // 获取保存的文件名
    NSString* pathFile = [self getDocumentDir];
    pathFile = [pathFile stringByAppendingPathComponent:@"staff.archi"];
    
    // 保存数据(归档)
    [data writeToFile:pathFile atomically:YES];
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Infomation" message:@"Archive finished" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
    [self textClear];
}
-(IBAction)onArchiverLoad:(id)sender
{
    // 获取保存的文件名
    NSString* pathFile = [self getDocumentDir];
    pathFile = [pathFile stringByAppendingPathComponent:@"staff.archi"];
    
    // 读取归档文件到内存(只读)
    NSData* data = [NSData dataWithContentsOfFile:pathFile];
    
    // 解码内存数据(只读)
    NSKeyedUnarchiver* unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    Staff* staff = [unarchiver decodeObjectForKey:@"staff"];
    [unarchiver finishDecoding];
    
    self._textNickName.text = staff._nickName;
    self._textEmail.text = staff._email;
    self._textPhone.text = staff._phone;
    self._textSex.text = staff._sex;
    self._textPosition.text = staff._position;
    
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Infomation" message:@"Load from Archiver finished" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


工程代码

IOS开发-数据持久化(一)【文本文件+二进制归档】