微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

NSTextAttachment 子类不支持安全编码,因为它覆盖了 -initWithCoder: 并且不覆盖 +supportsSecureCoding

如何解决NSTextAttachment 子类不支持安全编码,因为它覆盖了 -initWithCoder: 并且不覆盖 +supportsSecureCoding

我正在尝试将带有 textAttachments 的 NSAttributedString 保存到核心数据。

为此,我需要使用 this 对其进行转换,因为核心数据不再接受 NSKeyedUnarchiver

@objc(NSAttributedStringTransformer)
class NSAttributedStringTransformer: NSSecureUnarchiveFromDataTransformer {
    override class var allowedTopLevelClasses: [AnyClass] {
        return super.allowedTopLevelClasses + [NSAttributedString.self]
    }
}

转换器要求将所有内容转换为符合 NSSecureCoding

这很好用但是我在添加附件时使用 NSTextAttachment 的自定义子类:

final class ImageAttachment: NSTextAttachment {
    
    #if os(macOS)
        override func attachmentBounds(
            for textContainer: NSTextContainer?,proposedLineFragment lineFrag: NSRect,glyPHPosition position: CGPoint,characterIndex charIndex: Int
        ) -> NSRect {
            guard let image = self.image else {
                return super.attachmentBounds(
                    for: textContainer,proposedLineFragment: lineFrag,glyPHPosition: position,characterIndex: charIndex
                )
            }

            let aspectRatio = image.size.width / image.size.height
            let width = min(lineFrag.width,image.size.width)
            let height = width / aspectRatio

            return NSRect(x: 0,y: 0,width: width,height: height)
        }
    #else
        override func attachmentBounds(
            for textContainer: NSTextContainer?,proposedLineFragment lineFrag: CGRect,characterIndex charIndex: Int
        ) -> CGRect {
            guard let image = self.image else {
                return super.attachmentBounds(
                    for: textContainer,image.size.width)
            let height = width / aspectRatio

            return CGRect(x: 0,height: height)
        }
    #endif
}

这会产生以下错误

无法读取数据,因为它的格式不正确。,["NSUnderlyingError": Error Domain=NSCocoaErrorDomain Code=4864 "Class 'Noah.ImageAttachment' 有一个支持安全编码的超类,但是 ' Noah.ImageAttachment' 覆盖 -initWithCoder: 并且不覆盖 +supportsSecureCoding。该类必须实现 +supportsSecureCoding 并返回 YES 以验证其 -initWithCoder: 的实现是否符合安全编码。 UserInfo={NSDebugDescription=Class 'Noah.ImageAttachment' 有一个支持安全编码的超类,但 'Noah.ImageAttachment' 覆盖 -initWithCoder: 并且不覆盖 +supportsSecureCoding。该类必须实现 +supportsSecureCoding 并返回 YES 以验证其 -initWithCoder: 的实现是否符合安全编码。}]

我尝试按照指示添加

override public static var supportsSecureCoding: Bool{
        return true
    }

required convenience public init?(coder aDecoder: NSCoder) {

    self.init(coder: aDecoder)

}

然而,这会在 initWithCoder

线程 1:EXC_BAD_ACCESS(代码=2,地址=0x7ffee12f7ffc)

谁能帮我解决initWithCoder

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。