iOS-数据持久化之--归档

四种数据持久化方式总目录

2.归档

归档(archiving)也是指另一种形式的序列化,但是它是任何对象都可以实现的更常规的类型。尽管我们对归档的使用没有严格要求,我们一般要实现两个协议NSCoding协议和NSCoping协议。
NSCoding协议声明了2个方法:一个是将对象编码到归档中,另一个是对归档的解码来恢复我们之前归档的对象,使用方法与NSUserDefaults相似也可以用KVC对对象和原生数据类型(如int和float)进行编码和解码。

①对单个对象进行归档

使用NSKeyedArichiver进行归档、NSKeyedUnarchiver进行接档,这种方式会在写入、读出数据之前对数据进行序列化、反序列化操作。

归档:

NSString *homeDictionary = NSHomeDirectory();//获取根目录
NSString *homePath  = [homeDictionary stringByAppendingPathComponent:@"atany.archiver"];//添加储存的文件名
BOOL flag = [NSKeyedArchiver archiveRootObject:@”归档” toFile:homePath];//归档一个字符串

这种方式可以对字符串、数字等进行归档,当然也可以对NSArray与NSDictionary进行归档。返回值Flag标志着是否归档成功,YES为成功,NO为失败。

接档:

[NSKeyedUnarchiver unarchiveObjectWithFile:homePath]

使用NSKeyedUnarchiver进行接档(反序列化)。
**这种归档的方式存在一个缺点:只能把一个对象归档进一个文件中。

②对多个对象进行归档

同样是使用NSKeyedArchiver进行归档,不同的是同时归档多个对象,这里我们举例放入了一个CGPoint点、字符串、整数(当然很多类型都可以的,例如UIImage、float等等),使用encodeXXX方法进行归档,最后通过writeToFile方法写入文件。

归档:写入数据

//准备数据

CGPoint point = CGPointMake(1.0, 2.0);
NSString *info = @"坐标原点";

NSInteger value = 10;

NSString *multiHomePath = [NSHomeDirectory() stringByAppendingPathComponent:@"multi.archiver"];

NSMutableData *data = [[NSMutableData alloc]init];

NSKeyedArchiver *archvier = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

//对多个对象进行归档

[archvier encodeCGPoint:point forKey:@"kPoint"];

[archvier encodeObject:info forKey:@"kInfo"];

[archvier encodeInteger:value forKey:@"kValue"];

[archvier finishEncoding];

[data writeToFile:multiHomePath atomically:YES];

接档:从路径中获得数据构造NSKeyedUnarchiver实例,使用decodeXXXForKey方法获得文件中的对象。

NSMutableData *dataR = [[NSMutableData alloc]initWithContentsOfFile:multiHomePath];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:dateR];

CGPoint pointR = [unarchiver decodeCGPointForKey:@"kPoint"];

NSString *infoR = [unarchiver decodeObjectForKey:@"kInfo"];

NSInteger valueR = [unarchiver decodeIntegerForKey:@"kValue"];

[unarchiver finishDecoding];

NSLog(@"%f,%f,%@,%d",pointR.x,pointR.y,infoR,valueR);

**可以看出对多个对象进行归档还是挺方便的,这里又出现一个问题,这里的对象都是基本类型数据。

③对自定义对象进行归档

//这是我建立的两个类和一个APPDelegate类,归档的操作在ViewController中操作,Person是要被归档的类


iOS-数据持久化之--归档_第1张图片
1.png

**Person.h

@interface Person : NSObject

@property (copy,nonatomic) NSString *name;
@property (copy,nonatomic) NSString *age;
@property (copy,nonatomic) NSString *phone;

@end

**Person.m

@implementation Person

- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:_name forKey:@"name"];
    [aCoder encodeObject:_age forKey:@"age"];
    [aCoder encodeObject:_phone forKey:@"phone"];
    
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        _name = [aDecoder decodeObjectForKey:@"name"];
        _age = [aDecoder decodeObjectForKey:@"age"];
        _phone = [aDecoder decodeObjectForKey:@"phone"];
    }
    return self;
    
}

-(id)copyWithZone:(NSZone *)zone
{
    Person *copy = [[[self class] allocWithZone:zone] init];
    copy.name = [self.name copyWithZone:zone];
    copy.age = self.age;
    copy.phone = self.phone;
    
    return copy;
}
@end

**ViewController.m

#import "ViewController.h"
#import "Person.h"
#define KEY @"person"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    Person *per = [[Person alloc] init];
    per.name = @"阿杰";
    per.age = @"30";
    per.phone = @"1234567";
    //存储路径
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *demoPath = [path objectAtIndex:0];
    NSString *spath = [demoPath stringByAppendingPathComponent:@"Singel.archiver"];
    //归档
    NSMutableData *data = [NSMutableData new];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:per forKey:KEY];
    [archiver finishEncoding];
    Boolean result = [data writeToFile:spath atomically:YES];
    //拷贝(没有用per2这个类)
    Person *per2 = [per copy];

    if (result) {
        NSLog(@"归档成功:%@",spath);
    }
    //接档
    NSMutableData *uData = [[NSMutableData alloc] initWithContentsOfFile:spath];
    NSKeyedUnarchiver *uarchier = [[NSKeyedUnarchiver alloc] initForReadingWithData:uData];
    Person *uper = [uarchier decodeObjectForKey:KEY];
    
    NSLog(@"%@",uper.name);
    NSLog(@"%@",uper.age);
    NSLog(@"%@",uper.phone);
    
}

@end

Person实现了三个委托方法1)encodeWithCoder: 2)initWithCoder: 3)copyWithZone:

1)encodeWithCoder

Encodes the receiverusing a given archiver
通过一个给定的archiver把消息接收者进行编码。
当接收到encodeObject消息的时候,类终端encodeWithCoder方法被调用。

2)initWithCoder

Returns an objectinitialized from data in a given unarchiver. (required)
从一个给定unarchiver的数据中返回一个初始化对象。

3)copyWithZone

Returnsa new instance that’s a copy of the receiver
返回消息接收者的一个复制的新实例。

你可能感兴趣的:(iOS-数据持久化之--归档)