归档解档相较于NSUserDefaults和NSFileManager,可以存储任意类型对象,比如一个APP首页的列表页,如果要缓存数据,则可以考虑归档解档
1.新建一个基类MSModel
#import@interface MSModel : NSObject @end
#import "MSModel.h" #import@implementation MSModel - (instancetype)initWithCoder:(NSCoder *)aDecoder { if (self = [super init]) { u_int count; objc_property_t *properties = class_copyPropertyList([self class], &count); for (int i = 0; i < count; i++) { const char *propertyName = property_getName(properties[i]); NSString *key = [NSString stringWithUTF8String:propertyName]; [self setValue:[aDecoder decodeObjectForKey:key] forKey:key]; } free(properties); } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { u_int count; objc_property_t *properties = class_copyPropertyList([self class], &count); for (int i = 0; i < count; i++) { const char *propertyName = property_getName(properties[i]); NSString *key = [NSString stringWithUTF8String:propertyName]; [aCoder encodeObject:[self valueForKey:key] forKey:key]; } free(properties); } @end
2.以后创建需要缓存的模型就继承自MSModel即可实现缓存的目的
#import "MSModel.h" @interface CacheModel : MSModel @property (nonatomic, copy, nullable) NSString *name; @property (nonatomic, copy, nullable) NSString *ID; @property (nonatomic, assign) NSInteger *age; @property (nonatomic, assign) BOOL gender; @end
3.在控制器中实现缓存
// 归档 CacheModel *model = [CacheModel new]; model.name = @"moses"; model.ID = @"10086"; model.age = 18; model.gender = 1; NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *filePath = [documentPath stringByAppendingPathComponent:@"cache001"]; [NSKeyedArchiver archiveRootObject:model toFile:filePath];
// 解档 NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *filePath = [documentPath stringByAppendingPathComponent:@"cache001"]; CacheModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; NSLog(@"%@--%@--%d--%d", model.name, model.ID, model.age, model.gender);
作者:_moses
链接:http://www.jianshu.com/p/4e5b9d34bcb3
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。