对象数组序列化和反序列化

对象数组序列化需要对象实现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];
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值