NSLog(@"path=%@",path);
//3.将自定义的对象保存到文件中
[NSKeyedArchiver archiveRootObject:p toFile:path];
}
- (IBAction)readBtnOnclick:(id)sender {
//1.获取文件路径
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path=[docPath stringByAppendingPathComponent:@"person.yangyang"];
NSLog(@"path=%@",path);
//2.从文件中读取对象
YYPerson *p=[NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@,%d,%.1f",p.name,p.age,p.height);
}
@end
新建一个person类
YYPerson.h文件
复制代码//
// YYPerson.h
// 02-归档
//
// Created by apple on 14-6-7.
// Copyright (c) 2014年 itcase. All rights reserved.
//
#import <Foundation/Foundation.h>
// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface YYPerson : NSObject<NSCoding>
//姓名
@property(nonatomic,copy)NSString *name;
//年龄
@property(nonatomic,assign)int age;
//身高
@property(nonatomic,assign)double height;
@end
YYPerson.m文件
复制代码
//
// YYPerson.m
// 02-归档
//
// Created by apple on 14-6-7.
// Copyright (c) 2014年 itcase. All rights reserved.
//
#import "YYPerson.h"
@implementation YYPerson
// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"调用了encodeWithCoder:方法");
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];










