- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试为包含 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/
我是一名优秀的程序员,十分优秀!