归档(上)

归档

 

1> 概念:对象归档是一个过程,即某种格式来保存一个或多个对象,以便以后还原这些对象

在其它语言中,对象归档也叫对象序列化

 

2> 要对自定义的对象(而不是Foundation里默认的对象)进行归档的话就需要引入归档协议<NSCoding>

实现两个方法

-(void) encodeWithCoder: (NSCoder *) aCoder

-(id) initWithCoder: (NSCoder *) aDecoder

 

3> 对象归档方法

[NSKeyedArchiver  archiveRootObject: user1 toFile: filePath];

对象解归档方法

[NSKeyedUnarchiver  unarchiveObjectWithFile: filePath];

 

帮助大家深入理解:

 

归档过程: 它在后台创建一个NSKeyedArchiver实例,然后,它将NSKeyedArchiver实例传递给对象thing的-encodeWithCoder:方法。当thing编码自身的属性时,它可能对其他对象也进行编码,例如字符串,数组以及我们可能输入到该数组中的任何内容。整个对象集合完成键和值的编码后,具有键/值对的归档程序将所有对象扁平化为一个NSData类并将其返回.方法中的主要的参数就是NSCoder,它是archivie字节流的抽象类.可以将数据写入一个coder,也可以从coder中读取我们写入的数据. NSCoder是一个抽象类,不能直接使用它来创建对象. 但是可以通过其子类NSKeyedUnarchiver从字节流中读取数据,NSKeyedArchiver将对象写入到字节流

 

用个例子来解释一下 person类 

#import <Foundation/Foundation.h>

 

@interface Person : NSObject<NSCoding>

 

@property (nonatomic, copy) NSString * name;

@property (nonatomic, assign) int age;

@property (nonatomic, assign) double weight;

 

@end

 

 

 

#import "Person.h"

 

@implementation Person

 

//NSCoder抽象类

//归档

- (void)encodeWithCoder:(NSCoder *)aCoder {

    

    [aCoder encodeObject:self.name forKey:@"name"];

    [aCoder encodeInt:self.age forKey:@"age"];

    [aCoder encodeDouble:self.weight forKey:@"weight"];

    

}

 

//解档

- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {

    

    if (self = [super init]) {

        

        self.name = [aDecoder decodeObjectForKey:@"name"];

        self.age = [aDecoder decodeIntForKey:@"age"];

        self.weight = [aDecoder decodeDoubleForKey:@"weight"];

    }

    

    return self;

}

 

@end

 

主函数:

#import <Foundation/Foundation.h>

#import "Person.h"

 

void test()

{

    Person * p = [[Person alloc] init];

    p.name = @"dahuan";

    p.age = 18;

    p.weight = 100.0;

    

    BOOL isSuccess = [NSKeyedArchiver archiveRootObject:p toFile:@"/Users/dahuan/Desktop/test.txt"];

    if (isSuccess) {

        NSLog(@"归档成功");

    } else {

        NSLog(@"归档失败");

    }

}

 

int main(int argc, const char * argv[]) {

    @autoreleasepool {

 

        //解档

        Person * p = [NSKeyedUnarchiver unarchiveObjectWithFile:@"/Users/dahuan/Desktop/test.txt"];

        NSLog(@"%@",p.name);

        NSLog(@"%d",p.age);

        NSLog(@"%f",p.weight);

        

        

    }

    return 0;

}

 

posted @ 2016-01-09 20:45  豆豆小  阅读(133)  评论(0)    收藏  举报