* 归档是一种很常用的文件储存方法,几乎任何类型的对象都能够被归档储存(实际上是一种文件保存的形式),步骤如下
1、对象要遵守NSCoding协议
2、实现以下两个方法:
解档方法:
-(id)initWithCoder:(NSCoder *)aDecoder{}
归档方法:
-(void)encodeWithCoder:(NSCoder *)aCoder{}
3、进行文件的读写
写:
[NSKeyedArchiver archiveRootObject:accountModel toFile:accountPath];
读:
NKAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:accountPath];
具体实现如下:
(1)创建NKAccount文件,目录结构如图
(2)NKAccount.h的实现
#import <Foundation/Foundation.h>
@interface NKAccount :NSObject<NSCoding>
@property (nonatomic ,copy)NSString *Id;
@property (nonatomic ,copy)NSString *name;
@property (nonatomic ,assign)NSInteger age;
@end
(3)NKAccount.m的实现
#import "NKAccount.h"
@implementation NKAccount
-(id)initWithCoder:(NSCoder *)aDecoder
{
if (self = [superinit]) {
self.Id = [aDecoderdecodeObjectForKey:@"Id"];
self.name = [aDecoderdecodeObjectForKey:@"name"];
self.age = [aDecoderdecodeIntegerForKey:@"age"];
}
return self;
}
-(void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoderencodeObject:self.IdforKey:@"Id"];
[aCoderencodeObject:self.nameforKey:@"name"];
[aCoder encodeInteger:self.ageforKey:@"age"];
}
@end
(4)读写过程
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//创建AccountModel
NKAccount *accountModel = [[NKAccountalloc]init];
accountModel.Id =@"123455";
accountModel.name =@"zhangsan";
accountModel.age =12;
//创建路径
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)lastObject];
NSLog(@"documents路径:%@",documentPath);
NSString *accountPath = [documentPath stringByAppendingPathComponent:@"Account.data"];
//存储用户信息
[NSKeyedArchiverarchiveRootObject:accountModel toFile:accountPath];
//读取用户信息
NKAccount *account = [NSKeyedUnarchiverunarchiveObjectWithFile:accountPath];
NSLog(@"Id:%@",account.Id);
NSLog(@"Id:%@",account.name);
NSLog(@"Id:%ld",account.age);
}
(5)创建的文件路径