使用MJExtension进行自定义对象解档归档达到存储自定义对象的功能
UserInfoModel.h
在模型的.h 加上
@interface UserInfoModel : NSObject <NSCoding>
UserInfoModel.m
加上
//解档归档路径,名字随意
#define kNSKeyedArchPath [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"XXX.arch"]
@implementation UserInfoModel
//通过MJExtension实现解归档
MJCodingImplementation
//实现存和取两个函数
+ (void)saveUserInfoModel:(UserInfoModel *)model{
[NSKeyedArchiver archiveRootObject:model toFile:kNSKeyedArchPath];
}
+ (UserInfoModel *)getUserInfoModel{
return [NSKeyedUnarchiver unarchiveObjectWithFile:kNSKeyedArchPath];
}
@end
然后在需要的地方进行归档解档操作:
//存
UserInfoModel *model = [UserInfoModel mj_objectWithKeyValues:myInfoDict];
[UserInfoModel saveUserInfoModel:model];
//取
UserInfoModel *model = [UserInfoModel getUserInfoModel];
NSLog(@"%@",model.name);
它其实就帮我们实现了把所有属性都归档和反归档的操作,那么问题来了,加入我不想所有的文件都归档,我只想归档name和age属性,不想归档gay属性,那怎么办呢?其实MJExtension已经帮我们想好了,只需要调用一下:
[UserInfoModel setupIgnoredCodingPropertyNames:^NSArray *{
return @[@"gay"];
}];
网友评论