我正在尝试将NSAttributedString保存为RTFD,然后从已保存的RTFD恢复NSAttributedString。 (想法是我最终将RTFD保存在数据库中。)
我的问题是附件内容无法从字符串中恢复。如下所示,您可以看到该字符串确实对附件数据进行了编码。
这是一个复制问题的最小示例:
let originalContents = "foobar".data(using: String.Encoding.utf8)
let originalAttachment = NSTextAttachment(data: originalContents,ofType: "public.text")
let originalString = NSMutableAttributedString(string: "deadbeef")
originalString.append(NSMutableAttributedString(attachment: originalAttachment))
originalString.append(NSMutableAttributedString(string: "deadbeef"))
let savedRtfd = originalString.rtfd(from: NSRange(0..<originalString.length))!
let recoveredString = NSAttributedString(rtfd: savedRtfd,documentAttributes: nil)!
let recoveredAttachments = attachments(from: recoveredString) // See *definition below
let recoveredAttachment = recoveredAttachments[0]
我希望这将返回recoveredAttachment.contents == "foobar"
,但我得到的是
recoveredAttachement.contents == nil
。为什么不还原NSTextAttribute的内容?我在这里想念什么?
谢谢您的帮助!
-jeff
- 以上
attachments(from:NSAttributedString) -> Array<NSTextAttachment>
方法的定义:
func attachments(from s: NSAttributedString) -> Array<NSTextAttachment> {
var attachments: Array<NSTextAttachment> = []
s.enumerateAttribute(.attachment,in: NSRange(0..<s.length)) {
value,range,stop in
guard let a = value else {
return
}
attachments.append(a as! NSTextAttachment)
}
return attachments
}