码迷,mamicode.com
首页 > 其他好文 > 详细

数据存储之归档解档

时间:2014-04-30 15:34:09      阅读:396      评论:0      收藏:0      [点我收藏+]

标签:com   code   log   c   tar   t   string   tab   ble   int   文件   

归档也叫序列化,是将文件存在硬盘,解码是从硬盘还原
一、使用属性列表进行归档
  如果对象是NSString,NSDictionary,NSArray,NSData,NSNumber,NSDate,可以是使用writeToFile:atomically方法将数据写到文件,注意这种方式是明文。
  NSArray *inputArray = [NSArray arrayWithObjects:@“abc”, @“123”, @“qiaohaibin”];
  //写入文件 当前目录下test.plist
  //一般写入都是写入沙盒Documents下
  BOOL result = [inputArray writeToFile:@“test.plist” atomically:YES];
  if(!result){
    NSLog(@“fail to write to file”);
  }
  //读出文件
  NSArray *outputArray = [NSArray arrayWithContentsOfFile:@“test.plist”];
  NSLog(@“%@“, outputArray);
二、使用NSKeyedArchiver和NSkeyedUnarchiver进行归档和解档。
  //文件完整路径
  NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  NSString *fileName = [filePath stringByAppendingPathComponent:@“test.archive"];
  1.对上面所说的类和基本数据进行归档和解档
    //归档
    NSMutableData *inputData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:inputData];
    [archiver encodeObject:[NSArray arrayWithObject:@“qiaohaibin”] forKey:@“array”];
    [archiver encodeInt:24 forKey:@“age”];
    [archiver finishEncoding];
    BOOL result = [inputData writeToFile:fileName atomically:YES];
    if(!result){
      NSLog(@“fail to archive to file”);
    }
    //解档
    NSData *outputData = [NSMutaleData data];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:outputData];
    NSArray *array = [unarchiver decodeObjectForKey:@“array”];
    int age = [unarchiver decodeIntForKey:@“age”];
  2.自定义对象进行归档和解档(需要事项NSCoding协议)
    //归档时调用
    - (void)encodeWithCoder:(NSCoder *)aCoder{
      [aCoder encodeInt:_age forKey:@“AGE”];
      [aCoder encodeObject:_username forKey:@“USERNAME”];
    }

    //解档时调用
    - (id)initWithCoder:(NSCoder *)aDecoder{
      self.age = [aDecoder decodeObjectForKey:@“AGE”];
      self.username = [aDecoder decodeObjectForKey:@“USERNAME”];
    }

数据存储之归档解档,布布扣,bubuko.com

数据存储之归档解档

标签:com   code   log   c   tar   t   string   tab   ble   int   文件   

原文地址:http://www.cnblogs.com/dilin/p/3699588.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!