二.數(shù)據(jù)持久化之對象歸檔和反歸檔

對象的類以及每個成員對象都要實現(xiàn)NSCoding協(xié)議
第一種.多個對象歸檔成一個文件
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) {
        //添加一些測試數(shù)據(jù)
        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,保存到一個沙盒文件(也可以將新建,修改,刪除后的數(shù)據(jù)寫入到文件)
        [theData writeToFile:self.plistFilePath atomically:TRUE];
    }
}
//4.對象成員要實現(xiàn)NSCoding
//  Note.h
#import <Foundation/Foundation.h>
@interface Note : NSObject <NSCoding>

@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--實現(xiàn)NSCoding協(xié)議
- (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.反歸檔(解碼使用)

//獲取數(shù)據(jù)
- (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;
}

如果你發(fā)現(xiàn)本文對你有所幫助,如果你認為其他人也可能受益,請把它分享出去。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容