12、对象归档(序列化)的基本概念

·概念: 对象归档是指将对象写入文件保存在硬盘上,当再次重新打开程序时, 可以还原这些对象。你也可以称它为对象序列化、对象持久化
·数据持久性的方式

·NSKeyedArchiver——对象归档
·NSUserDefaults ·属性列表化(NSArray、NSDictionary保存文件)
·SQlite数据库、Core Data数据库

·归档的形式

·对Foundation库中对象进行归档
·自定义对象进行归档(需要实现归档协议,NSCoding)

我们就以数组为例,实现一个数组的序列化和反序列化

//---------数组的序列化和反序列化--------------
        /***归档对象****/
        NSArray *array = @[@"abc",@"123",@1234];
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent:@"test.arc"];
        BOOL success = [NSKeyedArchiver archiveRootObject:array toFile:path];
        if (success) {
            NSLog(@"archive success");
        }

        /***解归档****/
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent:@"test.arc"];
        NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"%@",array);        

自定义内容归档

·归档

·使用NSData实例作为归档的存储数据
·添加归档的内容(设置key与value) ·完成归档
·将归档数据存入磁盘中

·解归档

·从磁盘读取文件,生成NSData实例
·根据Data实例创建和初始化解归档实例
·解归档,根据key访问value的值


//------------自定义内容归档方式--------------
        /***归档对象**/
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent:@"archiver2.archiv"];
        NSMutableData *data = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
        NSArray *array = @[@"jack",@"tom"];
        [archiver encodeInt:100 forKey:@"age"];
        [archiver encodeObject:array forKey:@"names"];
        [archiver finishEncoding];
        [archiver release];

        BOOL success = [data writeToFile:path atomically:YES];
        if (success) {
            NSLog(@"archive success");
        }

        /***解归档对象**/
        NSString *homePath = NSHomeDirectory();
        NSString *path = [homePath stringByAppendingPathComponent:@"archiver2.archiv"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
        int age = [unArchiver decodeIntForKey:@"age"];
        NSArray *names = [unArchiver decodeObjectForKey:@"names"];
        [unArchiver release];
        NSLog(@"age=%d,names=%@",age,names);

自定义对象的归档基本概念

·自定义的对象要支持归档,需要实现NSCoding协议。
·NSCoding协议有两个方法,encodeWithCoder 方法对对象的属性数据做编
码处理。initWithCoder 解码归档数据来初始化对象
·实现NSCoding协议后,就能通过NSKeyedArchiver归档。
·示例:

//User.h
#import <Foundation/Foundation.h>

@interface User : NSObject<NSCoding>

@property(nonatomic,copy)NSString *name;
@property(nonatomic,copy)NSString *email;
@property(nonatomic,copy)NSString *password;
@property(nonatomic,assign)int age;

@end
//User.m
#import "User.h"

#define AGE @"age"
#define NAME @"name"
#define EMAIL @"email"
#define PASSWORD @"password"

@implementation User

//对属性编码,归档的时候会调用
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeInt:_age forKey:AGE];
    [aCoder encodeObject:_name forKey:NAME];
    [aCoder encodeObject:_email forKey:EMAIL];
    [aCoder encodeObject:_password forKey:PASSWORD];

}

//对属性解码,解归档调用
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self != nil) {
        _age = [aDecoder decodeIntForKey:AGE];
        _name = [[aDecoder decodeObjectForKey:NAME] copy];
        _email = [[aDecoder decodeObjectForKey:EMAIL] copy];
        _password = [[aDecoder decodeObjectForKey:PASSWORD] copy];

//        self.name = [aDecoder decodeObjectForKey:NAME];
//        self.email = [aDecoder decodeObjectForKey:EMAIL];
//        self.password = [aDecoder decodeObjectForKey:PASSWORD];

    }
    return self;
}

- (NSString *)description {
    NSString *str = [NSString stringWithFormat:@"age=%d,name=%@,email=%@,pass=%@",_age,_name,_email,_password];
    return str;
}

- (void)dealloc {
    [_password release];
    [_email release];
    [_name release];
    [super dealloc];
}

@end
//main.h
#import <Foundation/Foundation.h>
#import "User.h"

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

    @autoreleasepool {
        /*******归档******/
        User *user = [[User alloc] init];
        user.name = @"jack";
        user.age = 22;
        user.email = @"wxhl@qq.com";
        user.password = @"123456";

        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.archiver"];
        BOOL success = [NSKeyedArchiver archiveRootObject:user toFile:path];
        if (success) {
            NSLog(@"archive success");
        }
        [user release];

        /*******解归档******/
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"user.archiver"];
        User *user = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        NSLog(@"%@",user);

    }
    return 0;
}

归档总结

·归档和解归档的两种方式
·自定义对象如何归档,实现NSCoding协议。
·归档后的文件是加密的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值