NSCoding 是归档与解档的意思.
1.首先要获取存储的沙盒里,必须获取沙盒的路径.
/**沙盒的路径, 要将stu.data文件存储的Documents文件夹中,stringByAppendingPathComponent这个方法不用再拼接"/"*/
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"stu.data"];
/*创建数据模型/
Person 父类 属于NSObject
Strudent 子类 属于 Person的子类
#import <Foundation/Foundation.h>
@interface Person : NSObject<NSCoding>/**这里必须采用NSCoding这个协议*/
/**姓名*/
@property (strong, nonatomic) NSString *name;
/**年龄*/
@property (assign, nonatomic) NSInteger age;
@end
/**.m文件,实现NSCoding协议*/
#import "Person.h"
@implementation Person
/**当归档的时候会调用*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
/**把属性归档起来,并设置key*/
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
}
/**当解档的时候用调用*/
- (id)initWithCoder:(NSCoder *)aDecoder{
if (self = [super init]){
/**根据key解档存储的文件*/
self.name = [aDecoder decodeObjectForKey:@"name"];
self.age = [aDecoder decodeIntegerForKey:@"age"];
}
return self;
}
@end
/**strudent类*/
#import <Foundation/Foundation.h>
#import "Person.h"
@interface Strudent : Person
@property (strong, nonatomic) NSString *no;
@property (assign, nonatomic) NSInteger store;
@end
/**.m文件实现NSCoding协议*/
#import "Strudent.h"
@implementation Strudent
/**归档的实现的方法*/
- (void)encodeWithCoder:(NSCoder *)aCoder{
/**继承父类后,首先要先调用父类的方法传入aCoder*/
[super encodeWithCoder:aCoder];
[aCoder encodeObject:self.no forKey:@"no"];
[aCoder encodeInteger:self.store forKey:@"store"];
}
/**解档实现的方法*/
- (id)initWithCoder:(NSCoder *)aDecoder{
- /**继承父类后,首先要先调用父类的方法传入aDecoder*/
if (self = [super initWithCoder:aDecoder]) {
self.store = [aDecoder decodeIntegerForKey:@"store"];
self.no = [aDecoder decodeObjectForKey:@"no"];
}
return self;
}
@end
保存
/**新建数据模型*/
Strudent *stu = [[Strudent alloc] init];
stu.name = @"xingzai";
stu.age = 27;
stu.no = @"68";
stu.store = 100;
[NSKeyedArchiver archiveRootObject:stu toFile:path];
NSLog(@"%@",path);
读取
Strudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@- %d -- %@ --%d",stu.name,stu.age,stu.no,stu.store);