iOS NSKeyedUnarchiver归档和读取

使用NSKeyedUnarchiver归档数据到本地,很多时候保存的并不是基础数据类型,更多是自己定义的Model。有时会碰到归档或者读取的内容跟自己保存的数据类型不匹配。

现在按照思路一步一步解决:
1.先保存文件
保存的数据的类型

objectivec 复制代码
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HSFileModel : NSObject 

@property (nonatomic, strong) NSURL *fileUrl; //文件链接
@property (nonatomic, copy) NSString *fileName; //文件名

@end
objectivec 复制代码
@property (nonatomic, strong) NSMutableDictionary<NSString *, HSFileModel *> *selectedFilesData;

保存的数据到本地的方法

objectivec 复制代码
// 保存selectedFilesData到本地文件
- (void)saveSelectedFilesDataToLocal {
    // 获取文件路径
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // 拼接文件路径
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"SelectedFilesData.plist"];
    
    // 归档字典对象
    NSError *error = nil;
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.selectedFilesData requiringSecureCoding:YES error:&error];
    
    if (error) {
        NSLog(@"Error archiving data: %@", error);
    } else {
        // 将归档数据写入文件
        [data writeToFile:filePath atomically:YES];
    }
}

2.读取刚才保存的数据,确保读取的数据的文件路径跟保存的文件路径一致。

objectivec 复制代码
- (void)loadSelectedFilesDataFromLocal {
    // 获取文件路径
    // 获取文件路径
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    // 拼接文件路径
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"SelectedFilesData.plist"];

    // 尝试从文件中读取归档数据
    NSData *data = [NSData dataWithContentsOfFile:filePath];
    if (data) {
        // 解档数据为字典对象
        NSError *error = nil;
        self.selectedFilesData = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[NSMutableDictionary.class, NSString.class, HSFileModel.class, NSURL.class]] fromData:data error:&error];
        
        
        if (error) {
            NSLog(@"Error unarchiving data: %@", error);
            // 可以在此处理解档错误的情况
        }
    } else {
        // 如果文件不存在或读取失败,可以初始化一个空字典
        self.selectedFilesData = [NSMutableDictionary dictionary];
    }
}

当调用读取的方法的时候会有一个错误如下:

Printing description of error:

Error Domain=NSCocoaErrorDomain Code=4864 "This decoder will only decode classes that adopt NSSecureCoding. Class 'HSFileModel' does not adopt it." UserInfo={NSDebugDescription=This decoder will only decode classes that adopt NSSecureCoding. Class 'HSFileModel' does not adopt it.}

这因为保存的数据类型有自己定义的Model,而且HSFileModel没有实现NSSecureCoding协议导致不能解码。所有被编码和解码的类都必须遵循NSSecureCoding协议。

3.给HSFileModel实现NSSecureCoding协议

objectivec 复制代码
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HSFileModel :  NSObject <NSSecureCoding> 

@property (nonatomic, strong) NSURL *fileUrl; //文件链接
@property (nonatomic, copy) NSString *fileName; //文件名

@end
objectivec 复制代码
#import "HSFileModel.h"

@implementation HSFileModel
+ (BOOL)supportsSecureCoding {
    return YES;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.fileUrl forKey:@"fileUrl"];
    [coder encodeObject:self.fileName forKey:@"fileName"];
}

- (instancetype)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        self.fileUrl = [coder decodeObjectForKey:@"fileUrl"];
        self.fileName = [coder decodeObjectForKey:@"fileName"];
    }
    return self;
}


@end

4.对于 + (nullable id)unarchivedObjectOfClasses:(NSSet<Class> *)classes fromData:(NSData *)data error:(NSError **)error

使用这个方法解档的话,参数(NSSet<Class> *)classes应该传入目标数据可能包含的数据的数据类型的集合。比如:

objectivec 复制代码
   self.selectedFilesData = [NSKeyedUnarchiver unarchivedObjectOfClasses:[NSSet setWithArray:@[NSMutableDictionary.class, NSString.class, HSFileModel.class, NSURL.class]] fromData:data error:&error];

到此结束,如大佬有补充请指出。

相关推荐
国科安芯11 小时前
核电站仪控与监测系统中抗辐射 MCU 芯片应用研究
单片机·嵌入式硬件·macos·无人机·cocos2d·核电站
@大迁世界11 小时前
14个你现在必须关闭的 iOS 26 设置,不然手机很快被它榨干
macos·ios·智能手机·objective-c·cocoa
健忘的萝卜11 小时前
Clawdbot 爆红硅谷,也把 AI Agent 和 Mac mini 推上风口
人工智能·macos·agent·数字员工·clawbot
YJlio19 小时前
10.2.8 以其他账户运行服务(Running services in alternate accounts):为什么“把服务切到某个用户账号下运行”,本质上是在改变服务的整个安全上下文?
python·安全·ios·机器人·django·iphone·7-zip
HashFlag21 小时前
Mac新机基础配置
macos
承渊政道1 天前
【动态规划算法】(子序列问题解题框架与典型案例)
数据结构·c++·学习·算法·leetcode·macos·动态规划
pop_xiaoli1 天前
【iOS】KVC与KVO
笔记·macos·ios·objective-c·cocoa
SkyXZ~1 天前
Mac上使用VScode优雅开发STM32
vscode·stm32·macos
90后的晨仔1 天前
《swiftUI进阶 第10章:现代状态管理(iOS 17+)》
ios
brucelee1861 天前
Claude Code 安装教程(Windows / Linux / macOS)
linux·windows·macos