如何将包含属性字符串的对象编码为Data?

时间:2019-03-06 10:43:06

标签: swift encoding nsdata decoding nsdocument

我有一个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更简单的方法吗?)

0 个答案:

没有答案