1

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

为此,我需要将其转换核心数据不再接受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,
            glyphPosition position: CGPoint,
            characterIndex charIndex: Int
        ) -> CGRect {
            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 CGRect(x: 0, y: 0, width: width, height: height)
        }
    #endif
}

这会产生以下错误:

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

4

0 回答 0