归档可以实现把自定义的对象存放在文件中.
注意://遵守NSCoding协议,并实现该协议中的两个方法。
下面举个小例子详细介绍如何使用NSCoder
1.首先自定义一个Person类
#import <Foundation/Foundation.h>
@interface JYPerson : NSObject<NSCoding>
//姓名
@property(nonatomic,copy)NSString *name;
//年龄
@property(nonatomic,assign)int age;
//身高
@property(nonatomic,assign)double height;
@end
#import "JYPerson.h"
@implementation JYPerson
//遵守NSCoding协议,并实现该协议中的两个方法。
//将一个自定义对象保存到文件的时候就会调用该方法
//在该方法中说明如何存储自定义对象的属性,也就是说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"保存数据");
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeDouble:self.height forKey:@"height"];
}
//从文件中读取一个对象的时候就会调用该方法
//在该方法中说明如何读取保存在文件中的对象,也就是说清楚怎么读取文件中的对象
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"读取数据");
if(self=[super init])
{
self.name=[aDecoder decodeObjectForKey:@"name"];
self.age=(int)[aDecoder decodeIntegerForKey:@"age"];
self.height=[aDecoder decodeDoubleForKey:@"height"];
}
return self;
}
@end
2.在控制器对应的xib里拖两个butto控件,连线
//归档可以实现把自定义的对象存放在文件中
#import "ViewController.h"
#import "JYPerson.h"
@interface ViewController ()
- (IBAction)saveBtnClick:(id)sender;
- (IBAction)readBtnClick:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor=[UIColor orangeColor];
}
//保存数据
- (IBAction)saveBtnClick:(id)sender {
//1.创建对象
JYPerson *person=[[JYPerson alloc]init];
person.name=@"小悦悦";
person.age=24;
person.height=173.5;
//2.获取文件路径
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"person.gu"];
//3.将自定义的对象保存到文件中
[NSKeyedArchiver archiveRootObject:person toFile:path];
}
//读取数据
- (IBAction)readBtnClick:(id)sender {
//1.获取文件路径
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"person.gu"];
//2.从文件中读取对象
JYPerson *person=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"我看看读取的值是:%@ %d %lf",person.name,person.age,person.height);
}