gpt4 book ai didi

swift - 将 Codable 用于 NSAttributedString 时出错

转载 作者:搜寻专家 更新时间:2023-10-31 08:24:28 27 4
gpt4 key购买 nike

我正在尝试为包含 NSAttributedString 的类实现 Codable,但我在编译时遇到错误:

try container.encode(str, forKey: .str)

error ambiguous reference to member 'encode(_:forKey:)'

str = try container.decode(NSMutableAttributedString.self, forKey: .str)

error: No 'decode' candidates produce the expected contextual type 'NSAttributedString'

我可以通过使用字符串中的 NSData 来绕过它,但我认为这应该可行

class Text : Codable {
var str : NSAttributedString

enum CodingKeys: String, CodingKey {
case str
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(str, forKey: .str). <-- error ambiguous reference to member 'encode(_:forKey:)'
}

required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
str = try container.decode(NSMutableAttributedString.self, forKey: .str) <-- error: No 'decode' candidates produce the expected contextual type 'NSAttributedString'
}
}

最佳答案

NSAttributedString 不符合 Codable,所以你不能直接这样做。

如果您只想存储数据,您可以围绕符合 Codable 的属性字符串实现一个简单的包装器,并在您的数据类中使用它。这很容易,因为您可以使用 data(from:documentAttributes) 将属性字符串转换为 Data编码时。解码时,您首先读取数据,然后使用 init(data:options:documentAttributes:) 初始化属性字符串.它支持various data formats包括 HTML、RTF 和 Microsoft Word。

抵制在扩展中向 NSAttributedString 添加 Codable 一致性的诱惑。当 Apple 添加此一致性或您添加另一个执行此操作的库时,这将导致麻烦。

另一方面,如果您需要它与服务器或其他程序通信,则需要与所需的数据格式完全匹配。如果你只需要一个纯字符串,你可能根本不应该使用 NSAttributedString。如果它是其他格式,例如 markdown,您可以实现一个包装器来进行必要的转换。

关于swift - 将 Codable 用于 NSAttributedString 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49313371/

27 4 0
文章推荐: swift - 从 MTKView 创建的 UIImage 导致颜色/不透明度差异
文章推荐: java - cobertura vs 三叶草
文章推荐: html - 中的固定位置在 Firefox 和 Chrome 58 中不起作用