iOS学习ios开发

iOS开发之归档(NSKeyedArchiver)和反归档(NS

2017-03-09  本文已影响1630人  划满伤痕的天空

前言

iOS开发中难免会遇到数据存储的问题,苹果为我们提供了沙盒机制持久化存储数据 (iOS程序默认情况下只能访问程序自己的目录,这个目录被称为“沙盒”),这个就不详细介绍了。当遇到有结构有组织的数据时,譬如字典,数组,自定义的类等在存储时需要转换为字节流来存储。
比如今天我在写项目时自定义一个People类来方便的在其他地方调用用户数据,没网状态下也需要读取,所以需要在本地存储,而存储自定义对象就涉及到归档反归档操作了,可能有些人对这几个词概念还是比较模糊,简单说下这篇文章相关的几个专业名词的意思:

自定义对象的归档和反归档

 .h文件
 @interface People : NSObject<NSCoding>     // 给自定义类归档,首先要遵守NSCoding协议。
 @property (nonatomic, copy) NSString *name;
 @property (nonatomic, assign) NSUInteger age;
 @property (nonatomic, copy) NSString *address;
 .m文件
 @implementation People
 //序列化
- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
    [aCoder encodeObject:self.address forKey:@"address"];
}
 //反序列化
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    self = [super init];
    if (!self) { return nil; }
    self.name = [aDecoder decodeObjectForKey:@"name"];
    self.age = [aDecoder decodeIntegerForKey:@"age"];
    self.address = [aDecoder decodeObjectForKey:@"address"];
    return self;
}

NSKeyedArchiver和NSKeyedUnarchiver

  1. 对单个对象归档
//获取documents文件夹下对应的目录
- (NSString *)documentDirectory:(NSString *)filename{
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [documents stringByAppendingPathComponent:filename];
}

#pragma mark     单个对象进行归档及反归档
//归档
- (void)saveSingleObject:(id)object to:(NSString *)filename{
    NSString *path = [self documentDirectory:filename];
    BOOL success = [NSKeyedArchiver archiveRootObject:object toFile:path];
    NSLog(@"单个文件%@", success ? @"存储成功" : @"存储失败");
}
//反归档
- (id)loadSingleObjectFrom:(NSString *)filename{
    NSString *path = [self documentDirectory:filename];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { return nil; }
    id object = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return object;
}
//自定义对象的归档与反归档
    People *people = [[People alloc] init];
    people.name = @"star";
    people.age = 18;
    people.address = @"London";
//存储数据
    [self saveSingleObject:people to:@"people"];
//取出存储的数据, 可以通过NSLog看到输出的内容
    People *samePeople = [self loadSingleObjectFrom:@"people"];
    NSLog(@"%@", [samePeople description]);

温馨提醒:如果你一次性只是存储单个对象,正常开发中已经够用了,如果你想要存储多个对象,请往下看
2 . 对多个对象归档

#pragma mark     多个对象进行归档和反归档
//多个对象归档
- (void)saveMultipleObject:(id)object object1:(id)object1 to:(NSString *)filename{
    NSMutableData *data = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    //编码
    [archiver encodeObject:object forKey:@"key"];
    [archiver encodeObject:object1 forKey:@"key1"];
    [archiver finishEncoding];
    
    NSString *path = [self documentDirectory:filename];
    //说明:这里的atomically参数让该方法将数据写入辅助文件,而不是写入指定位置。成功写入该文件之后,辅助文件将被复制到第一个参数指定的位置。这是更安全的写入文件的方法,因为如果应用在保存期间崩溃,则现有文件(如果有)不会被破坏。尽管增加一点开销,但是多数情况下还是值得的。
    BOOL success = [data writeToFile:path atomically:YES];
    NSLog(@"多个文件%@", success ? @"存储成功" : @"存储失败");
}
//多个对象反归档
- (void)loadObjectFrom:(NSString *)filename block:(void(^)(id object, id object1))block{
    NSString *path = [self documentDirectory:filename];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) { return; }
    NSMutableData *data = [[NSMutableData alloc] initWithContentsOfFile:path];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    //解码
    id object = [unarchiver decodeObjectForKey:@"key"];
    id object1 = [unarchiver decodeObjectForKey:@"key1"];
    [unarchiver finishDecoding];
    
    if (!block) { return; }
    block(object, object1);
    
}

以上介绍的NSKeyedArchiver和NSKeyedUnarchiver的用法日常开发中基本上够用了,如果你还意犹未尽,可以深入学习,欢迎提出分享意见,共同进步!
你可以在这里下载项目:

点击进入github项目地址

上一篇 下一篇

猜你喜欢

热点阅读