#import <Foundation/Foundation.h>
@class User;
@interface CacheUtility : NSObject
+ (BOOL)archiveUserWithArray:(NSArray<User *> *)array;
+ (NSArray<User *> *)unArchiveUserFromCache;
+ (BOOL)writeToCacheFile:(id)collection;
+ (NSArray *)readArrayFromCacheFile;
@end
static NSString *const archiveFilePath = @"/Users/zhz/Desktop/test/zhz.plist";
static NSString *const writeFilePath = @"/Users/zhz/Desktop/test/zhz2.plist";
@implementation CacheUtility
+ (BOOL)archiveUserWithArray:(NSArray<User *> *)array {
BOOL isSuccess = [NSKeyedArchiver archiveRootObject:array toFile:archiveFilePath];
if (isSuccess) {
NSLog(@"archive--缓存成功");
} else {
NSLog(@"archive--缓存失败");
}
return isSuccess;
}
+ (NSArray<User *> *)unArchiveUserFromCache {
NSArray<User *> *array = [NSKeyedUnarchiver unarchiveObjectWithFile:archiveFilePath];
if (!array) {
array = [NSArray array];
}
return array;
}
+ (BOOL)writeToCacheFile:(id)collection {
if ([collection isKindOfClass:[NSDictionary class]]) {
NSDictionary *dict = (NSDictionary *)collection;
return [dict writeToFile:writeFilePath atomically:YES];
}else if( [collection isKindOfClass:[NSArray class]]){
NSArray *array = (NSArray *)collection;
return [array writeToFile:writeFilePath atomically:YES];
}
else if ([collection isKindOfClass:[NSString class]]) {
NSString *string = (NSString *)collection;
return [string writeToFile:writeFilePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
return NO;
}
+ (NSArray *)readArrayFromCacheFile {
NSArray *fetchArray = [NSArray arrayWithContentsOfFile:writeFilePath];
return fetchArray;
}
@end