-
不管是
NSUserDefaults
或者是 plist
都不能对自定义的对象进行存储, 这里可以利用OC提供的解归档
来实现,注意自定义模型要遵循<NSCoding>协议
。
Person.h文件
@interface Person : NSObject <NSCoding> //解归档需要遵循NSCoding协议,并实现相关方法
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger sex;
@property (nonatomic, assign) NSInteger age;
@end
Person.m文件
@implementation Person
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.sex forKey:@"sex"];
[aCoder encodeInteger:self.age forKey:@"age"];
// 若项目中使用了第三方YYModel,可直接使用下面这句代码
// [self yy_modelEncodeWithCoder:aCoder];
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
self.sex = [aDecoder decodeIntegerForKey:@"sex"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
// 若项目中使用了第三方YYModel,可直接使用下面这句代码
// [self yy_modelInitWithCoder:aDecoder];
}
return self;
}
@end
ViewController.m文件
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Person *person1 = [Person new];
person1.name = @"程序猿";
person1.sex = 1;
person1.age = 26;
Person *person2 = [Person new];
person2.name = @"程序媛";
person2.sex = 0;
person2.age = 27;
NSMutableArray *personArr = [NSMutableArray arrayWithCapacity:0];
[personArr addObject:person1];
[personArr addObject:person2];
// 这里以缓存模型数组为例,缓存单个模型对象,直接把对应模型数组参数给为模型对象即可(存取都要更改)
[self wirteToFile: personArr]; // 归档
[self readFromFile]; // 解档
}
// 归档
- (void)wirteToFile:(NSArray *)dataArray {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *document = [documentPaths lastObject];
NSString *documentPath = [document stringByAppendingPathComponent:@"person"];
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:dataArray];
if ([arrayData writeToFile:documentPath atomically:YES]) { // 此行代码必须写,否则归档不成功
NSLog(@"归档成功");
}
}
// 解档
- (void)readFromFile {
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *document = [documentPaths lastObject];
NSString *documentPath = [document stringByAppendingPathComponent:@"person"];
NSData *resultData = [NSData dataWithContentsOfFile:documentPath];
NSArray *resultArray = [NSKeyedUnarchiver unarchiveObjectWithData:resultData];
NSLog(@"%@",resultArray);
}
@end
网友评论