归档与解归档

5、对象的归档

概念:对象归档是指将对象写入文件保存在硬盘上,当再次又一次打开程序时,能够还原这些对象。亦能够称作对象序列号,对象持久化

5.1数据持久化的方式

NSKeyedArchiver---对象归档

NSUserDefaults

属性列表化(NSArray。NSDictionary保存文件)

SQLite数据库,CoreData

5.2 归档的形式
对Foundation库对象进行归档
自己定义对象进行归档(须要实现归档协议,NSCoding)
归档后的文件是加密的,属性列表是明文的
//归档 (序列化)   编码
    NSString*homeDirectory  = NSHomeDirectory();
    NSArray *array5 = @[@123,@456,@"999",@"000"];
    NSString*filePath = [homeDirectory stringByAppendingPathComponent:@"array.archive"];
    if ([NSKeyedArchiver archiveRootObject:array5 toFile:filePath]) {
        NSLog(@"archiver success");
    }
    //解归档(反序列化) 解码
    NSArray*unArray = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"new Array:%@",unArray);

6 自己定义内容归档
    6.1 归档
使用NSData实例作为归档的存储数据
加入归档的内容 (设置key和value)
完毕归档
将归档数据存入磁盘中
  6.2 解归档
从磁盘读取数据,生成NSData实例
依据Data实例创建和初始化归档实例
解归档,依据key訪问value的值
//    archiver 压缩程式
    //自己定义内容归档
    //归档  序列化  编码
    NSString*homePath = NSHomeDirectory();
    NSString*customfilePath= [homePath stringByAppendingPathComponent:@"customContent.archive"];
    NSMutableData*data = [NSMutableData data];
    NSKeyedArchiver*archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeFloat:50.0 forKey:@"weight"];
    [archiver encodeObject:@"Tim" forKey:@"name"];
    [archiver finishEncoding];
    [archiver release];
    [data writeToFile:customfilePath atomically:YES];
   
//    解归档
    //读取归档数据
    NSData*content = [NSData dataWithContentsOfFile:customfilePath];
    NSLog(@"%@",content);
    //解归档
    NSKeyedUnarchiver*unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:content];
    //解归档数据
    float weight = [unarchiver decodeFloatForKey:@"weight"];
    NSString*name = [unarchiver decodeObjectForKey:@"name"];
    NSLog(@"-----%f-------%@",weight,name);

7 自己定义对象的归档基本概念
  对象要支持归档,须要实现NSCoding协议
  NSCoding协议有两个方法,encodeWithCoder方法对对象的属性数据做编码处理,initWithCoder解码归档数据来初始化对象
     实现NSCoding协议后,就能通过NSKeyedArchiver归档.
//编码  obj----> data
- (void)encodeWithCoder:(NSCoder *)aCoder
{
//  <NSKeyedArchiver: 0x8e7c160> 
    NSLog(@"这是一个编码的方法,作用就是对当前类的属性进行一一编码--%@",aCoder);
   
//  对属性进行编码
    [aCoder encodeObject:_nameStr forKey:KEY_NAME];
    [aCoder encodeObject:_phoneStr forKey:KEY_PHONE];
}
//解码 data---> obj
- (id)initWithCoder:(NSCoder *)aDecoder
{
//  <NSKeyedUnarchiver: 0x8f4e910>
    NSLog(@"这是一个解码的方法,作用就是对保存在NSCoder对象中编过码的数据进行解码,在一一的赋值给当前类的属性。--- %@",aDecoder);

    self = [super init];
    if (self)
    {
//      这里的获得的解码过后的对象。用当前的属性保存,要使用self.
        self.nameStr = [aDecoder decodeObjectForKey:KEY_NAME];
        self.phoneStr = [aDecoder decodeObjectForKey:KEY_PHONE];
    }
    return self;
}

posted on 2017-07-20 10:37  yjbjingcha  阅读(210)  评论(0编辑  收藏  举报

导航