在model文件的.m文件中对模型中的属性字段做下列操作:
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.orderid forKey:@"orderid"];
[aCoder encodeInteger:self.busid forKey:@"busid"];
[aCoder encodeObject:self.mobile forKey:@"mobile"];
[aCoder encodeInteger:self.sitefrom forKey:@"sitefrom"];
[aCoder encodeFloat:self.distance forKey:@"distance"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [super init]) {
self.orderid = [aDecoder decodeObjectForKey:@"orderid"];
self.busid = [aDecoder decodeIntegerForKey:@"busid"];
self.mobile = [aDecoder decodeObjectForKey:@"mobile"];
self.sitefrom = [aDecoder decodeIntegerForKey:@"sitefrom"];
self.distance = [aDecoder decodeFloatForKey:@"distance"];
}
return self;
}
如果app中使用了MJExtension框架,该框架已经为我们实现了解归档操作,则不需要写上述代码,只需要在.m文件中导入头文件”MJExtension”,然后在.m文件的@implementation与@end之间添加一句MJCodingImplementation代码 就OK.
将数据持久化到本地:
//保存数据
[NSKeyedArchiver archiveRootObject:_ticketArray toFile:[self savePath]];
- (NSString *)savePath
{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:@"ticketArray.plist"];
return path;
}
取出本地存储的数据:
//取数据:
NSMutableArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:[self savePath]];