iOS-结构化数据存储,使用NSCoder 归档(序列化)&解归档(返序列化)


- (void)_archiveListDataWithArray:(NSArray *)modelArray {

    NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSString*cachesPath = [pathArray firstObject];

    NSFileManager *fileManger = [NSFileManager defaultManager];


    //创建文件夹

    NSString *dataPath = [cachesPath stringByAppendingPathComponent:@"HomeListData"];

    NSError*createError;

    [fileManger createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&createError];


    //创建文件

    NSString *listDataPath = [dataPath stringByAppendingPathComponent:@"listData"];

    //序列化

    NSData *listData = [NSKeyedArchiver archivedDataWithRootObject:modelArray requiringSecureCoding:YES error:nil];

    [fileManger createFileAtPath:listDataPath contents:listData attributes:nil];

    NSData*readListData = [fileManger contentsAtPath:listDataPath];

    ///反序列化

    id unarchiveObj = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithObjects:[NSArray class], [HomeListModel class], nil] fromData:readListData error:nil];

    //查询文件

    __unusedBOOLisExist = [fileManger fileExistsAtPath:listDataPath];

//    if (isExist) {

//        [fileManger removeItemAtPath:listDataPath error:nil];

//    }

    //更新文件

//    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:listDataPath];

//    [fileHandle seekToEndOfFile];

//    [fileHandle writeData:[@"def" dataUsingEncoding:NSUTF8StringEncoding] error:nil];

//    [fileHandle synchronizeFile];

//    [fileHandle closeFile];

}



#import "HomeListModel.h"

@implementation HomeListModel

#pragma mark - NSSecureCoding

- (nullable instancetype)initWithCoder:(NSCoder *)coder {

    self= [super init];

    if(self) {

        self.deptName= [coder decodeObjectForKey:@"deptName"];

        self.docName= [coder decodeObjectForKey:@"docName"];

        self.docGoodAtNames= [coder decodeObjectForKey:@"docGoodAtNames"];

        self.jobTitleName= [coder decodeObjectForKey:@"jobTitleName"];

        self.url= [coder decodeObjectForKey:@"url"];

    }

    return self;

}

- (void)encodeWithCoder:(NSCoder*)coder {

    [coder encodeObject:self.deptName forKey:@"deptName"];

    [coder encodeObject:self.docName forKey:@"docName"];

    [coder encodeObject:self.docGoodAtNames forKey:@"docGoodAtNames"];

    [coder encodeObject:self.jobTitleName forKey:@"jobTitleName"];

    [coder encodeObject:self.url forKey:@"url"];

}

+ (BOOL)supportsSecureCoding {

    return YES;

}

#pragma mark - public method

- (void)congifutationWithDic:(NSDictionary *)dic {

    self.deptName= dic[@"deptName"];

    self.docName= dic[@"docName"];

    self.docGoodAtNames = dic[@"docGoodAtNames"];

    self.jobTitleName = dic[@"jobTitleName"];

    self.url= dic[@"url"];

}

@end

你可能感兴趣的:(iOS-结构化数据存储,使用NSCoder 归档(序列化)&解归档(返序列化))