iOS 归档、NSCoding协议

一、归档介绍

1.归档是将数据持久化的一种方式,一般针对于比较复杂对象,比如自定义的对象,来进行数据持久化操作。

2.归档的对象需要遵循NSCoding协议,存储的时候调用encodeWithCoder:方法,读取的时候调用initWithCoder:方法。

3.将数据写入本地需要调用 [NSKeyedArchiver archiveRootObject:per toFile:filePath],filePath为存储的路径。

4.从本地读取数据需要调用[NSKeyedUnarchiver unarchiveObjectWithFile:filePath],filePath为存储的路径。

二、对自定义对象进行归档

1.自定义Person类服从NSCoding协议

#import 
#import 

@interface Person : NSObject 
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) int age;
@property (nonatomic, assign)  CGFloat height;
@end

2.实现协议方法encodeWithCoder:和initWithCoder:

#import "Person.h"

@implementation Person
//写入文件时调用 -- 将需要存储的属性写在里面
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeFloat:self.height forKey:@"height"];
}

//从文件中读取时调用 -- 将需要存储的属性写在里面
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.height = [aDecoder decodeFloatForKey:@"height"];
    }
    return self;
}
@end

3.写入与读取
写入:[NSKeyedArchiver archiveRootObject:per toFile:filePath]
读取: [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]

#import "ViewController.h"
#import "Person.h"
@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self saveModel];
    [self readModel];
}

//存储数据
- (void)saveModel {
    Person *per = [Person new];
    per.name = @"xiaoming";
    per.age = 18;
    per.height = 180;
    
    NSString *filePath = [self getFilePath];
    
    //将对象per写入
    [NSKeyedArchiver archiveRootObject:per toFile:filePath];
    
}
//读取数据
- (void)readModel {
    NSString *filePath = [self getFilePath];
    
    //取出per对象
    Person *per = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    NSLog(@"%@ -- %@ -- %d -- %.0f", per, per.name, per.age, per.height);
}
//获得全路径
- (NSString *)getFilePath {
    //获取Documents
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //在Documents下创建Person.data文件
    NSString *filePath = [doc stringByAppendingPathComponent:@"Person.data"];
    return filePath;
}
@end

readModel:方法中打印出存储的per对象相关信息,则对自定义对象Person数据持久化成功

你可能感兴趣的:(iOS 归档、NSCoding协议)