归档

归档属于存储的一种形式。你可以通过序列化和反序列化去处理数据,从而达到本地存储和读取数据的目的。

归档存储的数据格式为二进制流。

归档必须要实现NSCoding协议。下面是实现了NSCoding协议的一些常用的类

NSNumber, NSString, NSDictionary, NSArray, NSData, NSDate

可以直接对这些类的对象进行归档操作。如果要自定义归档,就要对归档的类手动实现NSCoding协议。

下面,贴上一个自定义的类的归档实现代码。

点h文件:AccountModel.h

@interface AccRegisterOrderModel : NSObject 

@property (nonatomic, strong) NSString *statusMessage;
@property (nonatomic, strong) NSArray *answers;
@property (nonatomic, assign) BOOL isEmailVerified;
@property (nonatomic, strong) NSDate *currentDate;

@end

点m文件:AccountModel.m

@implementation AccountModel

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.statusMessage = [aDecoder decodeObjectForKey:@"statusMessage"];
        self.answers = [aDecoder decodeObjectForKey:@"answers"];
        self.isEmailVerified = [aDecoder decodeBoolForKey:@"isEmailVerified"];
        self.currentDate = [aDecoder decodeObjectForKey:@"currentDate"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_statusMessage forKey:@"statusMessage"];
    [aCoder encodeObject:_answers forKey:@"answers"];
    [aCoder encodeBool:_isEmailVerified forKey:@"isEmailVerified"];
    [aCoder encodeObject:_currentDate forKey:@"currentDate"];
}

@end

将AccountModel进行实例化

AccountModel *accountModel = [[AccountModel alloc] init];
accountModel.statusMessage = @"reject";
accountModel.answers = @[@"1", @"2", @"3", @"4"];
accountModel.isEmailVerified = YES;
accountModel.currentDate = [NSDate date];

将对象进行序列化(存储数据)

NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@“accountFile”];
[NSKeyedArchiver archiveRootObject:accountModel toFile:filePath];

反序列化(读取数据)

AccountModel *unkeyedModel = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

这里你可以使用unkeyedModel里面的属性值了。


你可能感兴趣的:(个人小结,归档)