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

网友投稿 246 2022-10-31


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

对象数组序列化需要对象实现NSCoding协议: PPKeyWordEntity.h

#import @interface PPKeyWordEntity : NSObject@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];}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:target overrides the `ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES` build setting defined in `Pods/Target S
下一篇:SpringBoot 开发提速神器 Lombok+MybatisPlus+SwaggerUI
相关文章

 发表评论

暂时没有评论,来抢沙发吧~