归档
- 1.1. 简单归档:指把简单的字符串、数组等对象进行归档
// 初始化需要归档的数组
NSArray *array = @[@"a", @"b", @"c"];
// 创建归档文件存储路径
NSString *path = PATH_AT_Tmp(@"file.archive"); // 文件后缀随意
// 归档
[NSKeyedArchiver archiveRootObject:array toFile:path];
// 解归档
NSArray *tempArray = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
// 输出打印
NSLog(@"kkk --- %@", tempArray);
- 1.2. data归档:先新建一个可变的data对象,然后通过创建一个NSKeyedArchiver实例对象对各种类型的数据进行归档到data的归档文件中
// 创建归档文件存储路径
NSString *path = PATH_AT_Tmp(@"file.archive");
// 创建可变data
NSMutableData *data = [NSMutableData data];
// 创建归档实例
NSKeyedArchiver *keyArch = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
// 归档
[keyArch encodeObject:@"勇往直前" forKey:@"name"];
[keyArch encodeInteger:18 forKey:@"age"];
[keyArch finishEncoding];
[data writeToFile:path atomically:YES];
// 解归档
NSData *outData = [NSData dataWithContentsOfFile:path];
NSKeyedUnarchiver *keyUnarch = [[NSKeyedUnarchiver alloc] initForReadingWithData:outData];
NSString *name = [keyUnarch decodeObjectForKey:@"name"];
NSInteger age = [keyUnarch decodeIntegerForKey:@"age"];
NSLog(@"name: %@, age: %ld", name, (long)age);
- 1.3. 自定义归档
定义一个类UserInfoModel,需遵守NSCoding协议
UserInfoModel.h文件中定义name、age和sex三个属性
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface UserInfoModel : NSObject<NSCoding>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *sex;
@end
NS_ASSUME_NONNULL_END
UserInfoModel.m文件需要重写一个归档方法、一个解归档方法
#import "UserInfoModel.h"
@implementation UserInfoModel
// 重写归档方法,把调用者的属性进行归档
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:self.name forKey:@"name"];
[coder encodeInteger:self.age forKey:@"age"];
[coder encodeObject:self.sex forKey:@"sex"];
}
// 重写解归档方法,把属性赋值给新对象的对应属性
- (instancetype)initWithCoder:(NSCoder *)coder
{
self = [super init];
if (self) {
self.name = [coder decodeObjectForKey:@"name"];
self.age = [coder decodeIntegerForKey:@"age"];
self.sex = [coder decodeObjectForKey:@"sex"];
}
return self;
}
@end
// 初始化对象
UserInfoModel *model = [[UserInfoModel alloc] init];
model.name = @"遇见";
model.age = 18;
model.sex = @"Man";
// 创建归档文件存储路径
NSString *path = PATH_AT_Tmp(@"file.archive");
// 归档
[NSKeyedArchiver archiveRootObject:model toFile:path];
// 解归档
UserInfoModel *outModel = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
// 输出
NSLog(@"name: %@, age: %ld, sex: %@", outModel.name, (long)outModel.age, outModel.sex);
https://www.haomeiwen.com/subject/pigdrrtx.html