创建一个工程,为ViewController。
新建两个类为NJperson
NJperson.h
#import <Foundation/Foundation.h>
// 如果想将一个自定义对象保存到文件中必须实现NSCoding协议
@interface NJPerson : NSObject <NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign) double height;
@end
NJperson.m
#import "NJPerson.h"
@implementation NJPerson
// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
- (void)encodeWithCoder:(NSCoder *)encoder
{
NSLog(@"NJPerson encodeWithCoder");
[encoder encodeObject:self.name forKey:@"name"];
[encoder encodeInteger:self.age forKey:@"age"];
[encoder encodeFloat:self.height forKey:@"heigth"];
}
// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
- (id)initWithCoder:(NSCoder *)decoder
{
NSLog(@"NJPerson initWithCoder");
if (self = [super init]) {
self.name = [decoder decodeObjectForKey:@"name"];
self.age = [decoder decodeIntegerForKey:@"age"];
self.height = [decoder decodeFloatForKey:@"heigth"];
}
return self;
}
_______在项目中创建两个按钮:一个为save,一个为read。
- (void)saveBtnClick:(id)sender{
NJStudent *stu = [[NJStudent alloc] init];
stu.name = @"lnj";
stu.age = 28;
stu.height = 1.8;
// 2.获取文件路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
NSLog(@"path = %@", path);
// 3.将自定义对象保存到文件中
[NSKeyedArchiver archiveRootObject:stu toFile:path];
}
- (void)readBtnClick:(id)sender {
// 1.获取文件路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"stu.xxoo"];
// 2.从文件中读取对象
// NJPerson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}