#define kactivityNum @"activityNum"
#define kalsoNeedKll @"alsoNeedKll"
@interface UserModel () <</span>NSCoding>
@end
添加代理的方法并且实现
- (id)initWithCoder:(NSCoder *)aDecoder
{
if (self == [super init]) {
self.activityNum = [aDecoder decodeObjectForKey:kactivityNum];
self.alsoNeedKll = [aDecoder decodeObjectForKey:kalsoNeedKll];
。。。。。。。。。。。
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.activityNum forKey:kactivityNum];
[aCoder encodeObject:self.alsoNeedKll forKey:kalsoNeedKll];
。。。。。。。。。。。
}
///归档
//需要用NSMutableData来中中介
NSMutableData *data = [[NSMutableData alloc] init];
//创建归档辅助类
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
//编码
[archiver encodeObject:user forKey:@"user"];
//结束编码
[archiver finishEncoding];
//写入
[data writeToFile:[self getFilePathWithModelKey:@"model"] atomically:YES];
///解档
NSData *_data = [[NSData alloc] initWithContentsOfFile:[selfgetFilePathWithModelKey:@"model"]];
//解档辅助类
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:_data];
//解档出数据模型Student
//解码并解档出model
UserModel *mStudent = [unarchiver decodeObjectForKey:@"user"];
//关闭解档
[unarchiver finishDecoding];
//得到Document目录
-(NSString *) getFilePathWithModelKey:(NSString *)modelkey
{
NSArray *array = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
return [[array objectAtIndex:0] stringByAppendingPathComponent:modelkey];
}