對象數組序列化和反序列化

對象數組序列化需要對象實現NSCoding協議:
PPKeyWordEntity.h

#import <Foundation/Foundation.h>


@interface PPKeyWordEntity : NSObject<NSCoding>

@property (nonatomic, strong) NSString *keyword;

- (instancetype)initWithKeyWord:(NSString *)keyWord;
- (void)fillDataWithKeyWord:(NSString *)keyWord;
@end

PPKeyWordEntity.m

#import "PPKeyWordEntity.h"

@implementation PPKeyWordEntity

- (instancetype)init
{
    self = [super init];
    if (self) {

    }
    return self;
}

- (instancetype)initWithKeyWord:(NSString *)keyWord
{
    if (self = [super init]) {
        [self fillDataWithKeyWord:keyWord];
    }
    return self;
}

- (void)fillDataWithKeyWord:(NSString *)keyWord
{
    self.keyword = keyWord;
    if(isCommonUnitEmptyString(keyWord))
    {
        return;
    }
    _keyword = keyWord;
}


-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:getNotNilString(self.keyword) forKey:@"keyword"];
    [aCoder encodeObject:[NSString stringWithFormat:@"%.0f", self.keywordWidth] forKey:@"keywordWidth"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self=[super init])
    {
        self.keyword = [aDecoder decodeObjectForKey:@"keyword"];
        self.keywordWidth = [[aDecoder decodeObjectForKey:@"keywordWidth"] floatValue];
    }
    return self;
}


@end

獲取文件路徑:

//  返回文件路徑
- (NSString *)getPathWithFileName:(NSString *)fileName
{
    NSString *newFileName = fileName;
    if(isFileHandleEmptyString(fileName))
    {
        newFileName = @"";
    }
    NSString *documents = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *path = [documents stringByAppendingPathComponent:fileName];
    return path;
}

對象數組序列化:

-(void)storeSearchHistoryListWithIsClearAll:(BOOL)isClearAll
{
    if(isClearAll)
    {
        [self.searchListEntity.searchHistoryList removeAllObjects];
    }
    else if(isEmptyArray(self.searchListEntity.searchHistoryList))
    {
        return;
    }
    [NSKeyedArchiver archiveRootObject:self.searchListEntity.searchHistoryList toFile:[self getPathWithFileName:@"Abc.archiver"]];
}

對象數組反序列化:

- (void)loadSearchHistoryList
{
    [self.searchListEntity.searchHistoryList removeAllObjects];
    NSString *searchHistoryPath = [self getPathWithFileName:@"Abc.archiver"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:searchHistoryPath]) {
        self.searchListEntity.searchHistoryList = [NSKeyedUnarchiver unarchiveObjectWithFile:searchHistoryPath];
    }
    [_searchListEntity updateKeywordLabelWidth];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章