对象数组序列化需要对象实现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]; }