二.数据持久化之对象归档和反归档

对象的类以及每个成员对象都要实现NSCoding协议
第一种.多个对象归档成一个文件
1.归档(编码归档)

@interface NSString (filePath)
-(NSString *)documentsFilePath;
@end
@implementation NSString (filePath)
-(NSString *)documentsFilePath
{
    NSString * documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject];
    NSString * filePath = [documentsPath stringByAppendingString:self];
    return filePath;
}
@end

#define kFirstDataPath @“/first.archive"
#define kSecondDataPath @"/second.archive"
#define ARCHIVE_KEY @"dataArray"

self.plistFilePath = [kFirstDataPath documentsFilePath];
//初始化文件
- (void)createArchiveFileIfNeeded {

    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL dbexits = [fileManager fileExistsAtPath:self.plistFilePath];

    if (!dbexits) {
        //添加一些测试数据
        NSDateFormatter *aDataFormatter = [[NSDateFormatter alloc] init];
        [aDataFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date1 = [aDataFormatter dateFromString:@"2016-10-01 16:01:03"];
        Note *note1 = [[Note alloc] initWithDate:date1 content:@"welcome to 317hu"];

        NSMutableArray *array = [[NSMutableArray alloc] init];
        [array addObject:note1];

        //1.构造archiver对象
        NSMutableData *theData = [NSMutableData data];
        NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:theData];
        //2.用指定key归档多个对象
        [archiver encodeObject:array forKey:ARCHIVE_KEY];
        [archiver encodeObject:@"tony" forKey:@"name"];
       //2.1结束归档编码
        [archiver finishEncoding]; //No more values can be encoded after this method is called. You must call this method when finished.
        //3.将归档好的data,保存到一个沙盒文件(也可以将新建,修改,删除后的数据写入到文件)
        [theData writeToFile:self.plistFilePath atomically:TRUE];
    }
}
//4.对象成员要实现NSCoding
//  Note.h
#import 
@interface Note : NSObject 

@property(nonatomic, strong) NSDate *date;
@property(nonatomic, strong) NSString *content;
- (instancetype)initWithDate:(NSDate *)date content:(NSString *)content;
- (instancetype)init;
@end
//  Note.m
#import "Note.h"

@implementation Note

- (instancetype)initWithDate:(NSDate *)date content:(NSString *)content {
    self = [super init];
    if (self) {
        _date = date;
        _content = content;
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _date = [[NSDate alloc] init];
        _content = @"";
    }
    return self;
}

#pragma mark--实现NSCoding协议
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:_date forKey:@"date"];
    [aCoder encodeObject:_content forKey:@"content"];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    _date = [aDecoder decodeObjectForKey:@"date"];
    _content = [aDecoder decodeObjectForKey:@"content"];
    return self;
}

@end

2.反归档(解码使用)

//获取数据
- (NSMutableArray *)getDataArray {

    NSData *theData = [NSData dataWithContentsOfFile:self.plistFilePath];

    if ([theData length] > 0) {
        //5.构建unArchiver对象
        NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:theData];
        NSMutableArray *listData = [unArchiver decodeObjectForKey:ARCHIVE_KEY];
        //5.1 解码完成
        [unArchiver finishDecoding];//Invoking this method allows the receiver to notify its delegate and to perform any final operations on the archive. Once this method is invoked, the receiver cannot decode any further values.

        return listData;
    }
    return nil;
}

第二种:一个对象归档成一个文件(对象和对象成员也要支持 NSCoding)
不需要[archiver finishEncoding]和[unArchiver finishDecoding],因为只有一个对象

#pragma mark - ArchiverAndUnArchiver
//归档
-(void)archiveMethod
{
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:note1];
    //1.归档对应到一个文件
    [NSKeyedArchiver archiveRootObject:array toFile:[kSecondDataPath documentsFilePath]];
}
//解档
-(void)unarchiverMethod
{
    //2.获得反归档的对象
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithFile:[kSecondDataPath documentsFilePath]];
    //使用
    self.data = array;
}

如果你发现本文对你有所帮助,如果你认为其他人也可能受益,请把它分享出去。

你可能感兴趣的:(二.数据持久化之对象归档和反归档)