首页 > 其他 > 详细

数据存储之归档解档

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

归档也叫序列化,是将文件存在硬盘,解码是从硬盘还原
一、使用属性列表进行归档
  如果对象是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

数据存储之归档解档

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!