我有一个NSDocument
子类,其中包含NSAttributedString
类型的属性(以及其他属性)。为了启用持久性,我需要重写以下两种方法:
override func data(ofType typeName: String) throws -> Data {
// Insert code here to write your document to data of the specified type, throwing an error in case of failure.
// TO BE IMPLEMENTED...
}
override func read(from data: Data, ofType typeName: String) throws {
// Insert code here to read your document from the given data of the specified type, throwing an error in case of failure.
// TO BE IMPLEMENTED...
}
如何将文档编码为Data
对象,我可以从第一种方法返回该文档,然后在需要时使用read(from:ofType:)
方法进行解码?
Codable
协议和NSKeyedArchiver
似乎是实现此目标的关键组件。但是,当我尝试使用以下方式对属性字符串进行编码时:
convenience init(from decoder: Decoder) throws {
self.init()
do {
let values = try decoder.container(keyedBy: CodingKeys.self)
attributedString = values.decode(NSAttributedString.Type, forKey: .attributedString)
} catch {
// ...
}
}
我收到编译器错误:
没有“解码”候选者产生预期的上下文结果类型
NSAttributedString
NSAttributedString
似乎不支持编码/解码,但是根据文档,它符合NSSecureCoding
,它继承自NSCoding
。
如何编码整个文档及其所有属性,包括属性字符串?
(有比使用NSKeyedArchiver
更简单的方法吗?)