iOS NSKeyedUnarchiver归档和读取

news/2024/7/20 22:13:44 标签: ios, macos
使用NSKeyedUnarchiver归档数据到本地,很多时候保存的并不是基础数据类型,更多是自己定义的Model。有时会碰到归档或者读取的内容跟自己保存的数据类型不匹配。

现在按照思路一步一步解决:

1.先保存文件

保存的数据的类型
 
#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HSFileModel : NSObject 

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

@end
@property (nonatomic, strong) NSMutableDictionary<NSString *, HSFileModel *> *selectedFilesData;

 保存的数据到本地的方法

// 保存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.读取刚才保存的数据,确保读取的数据的文件路径跟保存的文件路径一致。

- (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协议
 

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface HSFileModel :  NSObject <NSSecureCoding> 

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

@end
#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应该传入目标数据可能包含的数据的数据类型的集合。比如:

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

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


http://www.niftyadmin.cn/n/5146396.html

相关文章

【随手记】np.random.choice()函数

np.random.choice() 是 NumPy 中的一个随机抽样函数&#xff0c;用于从给定的一维数组中随机抽取指定数量或指定概率的元素。该函数可以用于构建模拟实验、生成随机数据集、数据抽样等应用场景。 np.random.choice(a, sizeNone, replaceTrue, pNone) 的参数如下&#xff1a; …

使用IO完成端口实现简单回显服务器

说明 使用IO完成端口实现简单回显服务器&#xff0c;因为是测试用的&#xff0c;所以代码很粗糙。 提醒 使用的是ReadFile、WriteFile来实现Overlapped IO&#xff0c;正式场合应该用WSARecv、WSASend&#xff0c;原因&#xff1a;来自《Windows网络编程技术》 8.2.5节 在这里…

Python模块ADB的, 已经 pyadb

Python模块ADB的使用指南_笔记大全_设计学院 (python100.com) pip install adb Python 调用ADB_python 调用adb命令_实相实相的博客-CSDN博客 Python ADB.shell_command Examples, pyadb.ADB.shell_command Python Examples - HotExamples Gitee 极速下载/PyADB - 码云 - 开…

王坚院士:云计算与 GPT 的关系,就是电和电动机的关系

无论是行业&#xff0c;还是阿里&#xff0c;都身处巨变时。已经年过六十的王坚院士&#xff0c;重回阿里&#xff0c;重回大众视野&#xff0c;今年以来&#xff0c;在多个场合都能够看到他的身影。 而每一次他的分享&#xff0c;都值得我们细细品味。 以下为王坚院士在 202…

leetcode做题笔记209. 长度最小的子数组

给定一个含有 n 个正整数的数组和一个正整数 target 。 找出该数组中满足其总和大于等于 target 的长度最小的 连续子数组 [numsl, numsl1, ..., numsr-1, numsr] &#xff0c;并返回其长度。如果不存在符合条件的子数组&#xff0c;返回 0 。 示例 1&#xff1a; 输入&#…

力扣刷题 day63:11-02

1.字符串中的第一个唯一字符 给定一个字符串 s &#xff0c;找到 它的第一个不重复的字符&#xff0c;并返回它的索引 。如果不存在&#xff0c;则返回 -1 。 方法一&#xff1a;两次遍历哈希表 #方法一&#xff1a;两次遍历哈希表 def firstUniqChar(s):d{}for i in s:if …

vue style里面写逻辑 写三元表达式

如下&#xff0c;一个简单的demo <div:style"{ display: isShow ? : none }"/>

vue3的computed源码解析

computed内部实现原理 一句话总结: computed是一个函数&#xff0c;该函数返回"一个通过ComputedRefImpl类实例化的对象"。 详情介绍: computed函数接收“一个有返回值的函数fn”&#xff0c;computed函数内部再将fn传递给ComputedRefImpl类进行实例化&#xff0c;C…