一、归档介绍
1.归档是将数据持久化的一种方式,一般针对于比较复杂对象,比如自定义的对象,来进行数据持久化操作。
2.归档的对象需要遵循NSCoding协议,存储的时候调用encodeWithCoder:方法,读取的时候调用initWithCoder:方法。
3.将数据写入本地需要调用 [NSKeyedArchiver archiveRootObject:per toFile:filePath],filePath为存储的路径。
4.从本地读取数据需要调用[NSKeyedUnarchiver unarchiveObjectWithFile:filePath],filePath为存储的路径。
二、对自定义对象进行归档
1.自定义Person类服从NSCoding协议
1 2 3 4 5 6 7 8 |
#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface Person : NSObject <NSCoding> @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) int age; @property (nonatomic, assign) CGFloat height; @end |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#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 |
写入:[NSKeyedArchiver archiveRootObject:per toFile:filePath] 读取: [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
#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 |