归档是iOS开发中数据存储常用的技巧,归档可以直接将对象储存成文件,把文件读取成对象。相对于plist或者userdefault形式,归档可以存储的数据类型更加多样,并且可以存取自定义对象。对象归档的文件是保密的,在磁盘上无法查看文件中的内容,更加安全。
+ (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path;
+ (nullable id)unarchiveObjectWithFile:(NSString *)path;
基本数据类型 序列化归档示例
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:
@"xiaoming", @"name",
@15, @"age",
@"1234567", @"studentid",
@"boy", @"sex",nil];
NSArray *array = @[@"数据1",@"数据2",@"数据3",@"数据4"];
NSString *docPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSString *path1 =[docPath stringByAppendingPathComponent:@"person.archiver"];//后缀名可以随意命名
NSString *path2 =[docPath stringByAppendingPathComponent:@"data.archiver"];
BOOL flag1 = [NSKeyedArchiver archiveRootObject:array toFile:path1];
BOOL flag2 = [NSKeyedArchiver archiveRootObject:dic toFile:path2];
反序列化解档
NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:path1];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile:path2];
自定义类型归档
#import <Foundation/Foundation.h>
// 归档自定义对象该对象必须实现nscoding 协议
@interface person : NSObject<NSCoding>
@property (nonatomic,copy) NSString *name;
@property (nonatomic,assign) NSInteger age;
@property (nonatomic,assign) double height;
@end
#import "person.h"
@implementation person
// 当将一个自定义对象保存到文件的时候就会调用该方法
// 在该方法中说明如何存储自定义对象的属性
// 也就说在该方法中说清楚存储自定义对象的哪些属性
-(void)encodeWithCoder:(NSCoder *)aCoder
{
NSLog(@"调用了encodeWithCoder:方法");
[aCoder encodeObject:self.name forKey:@"name"];
[aCoder encodeInteger:self.age forKey:@"age"];
[aCoder encodeDouble:self.height forKey:@"height"];
}
// 当从文件中读取一个对象的时候就会调用该方法
// 在该方法中说明如何读取保存在文件中的对象
// 也就是说在该方法中说清楚怎么读取文件中的对象
-(id)initWithCoder:(NSCoder *)aDecoder
{
NSLog(@"调用了initWithCoder:方法");
//注意:在构造方法中需要先初始化父类的方法
if (self=[super init]) {
self.name=[aDecoder decodeObjectForKey:@"name"];
self.age=[aDecoder decodeIntegerForKey:@"age"];
self.height=[aDecoder decodeDoubleForKey:@"height"];
}
return self;
}
@end
测试示例:
person *xiaoMu = [[person alloc] init];
xiaoMu.name = @"小木";
xiaoMu.age = 25;
xiaoMu.height = 180;
// 获取文件路径
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *path = [docPath stringByAppendingPathComponent:@"person.arch"];
// 保存自定义对象
[NSKeyedArchiver archiveRootObject:xiaoMu toFile:path];
// 解档
person *person2 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
NSLog(@"%@,%d,%.1fcm",person2.name,person2.age,person2.height);
网友评论