CoreData - 存储一个可转换对象数组

CoreData - Store an array of Tranformable objects

我有一个可以变形的实体 属性。它是一个自定义对象数组,Reminder 确认 NSSecureCoding

@objc(Reminder)
public class Reminder: NSObject, NSSecureCoding {
    public static var supportsSecureCoding: Bool = true
    
    
    public var date: Date
    public var isOn: Bool
    
    public  init(date: Date, isOn: Bool) {
        self.date = date
        self.isOn = isOn
    }
    
    struct Keys {
        static var date: String = "date"
        static let isOn: String = "isOn"
    }
    
    public func encode(with aCoder: NSCoder) {
        aCoder.encode(date as NSDate,forKey: Keys.date)
        aCoder.encode(isOn,forKey: Keys.isOn)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        guard let date = aDecoder.decodeObject(of: NSDate.self, forKey: Keys.date) as Date? else {
            return nil
        }
        
        self.date = date
        self.isOn = aDecoder.decodeBool(forKey: Keys.isOn)
    }
}

而下面的代码是我的NSSecureUnarchiveFromDataTransformer.

class ReminderDataTransformer: NSSecureUnarchiveFromDataTransformer {

    override class func allowsReverseTransformation() -> Bool {
        return true
    }

    override class func transformedValueClass() -> AnyClass {
        return Reminder.self
    }

    override class var allowedTopLevelClasses: [AnyClass] {
        return [Reminder.self]
    }

    override func transformedValue(_ value: Any?) -> Any? {
        guard let data = value as? Data else {
            fatalError("Wrong data type: value must be a Data object; received \(type(of: value))")
        }
        return super.transformedValue(data)
    }

    override func reverseTransformedValue(_ value: Any?) -> Any? {
        guard let reminder = value as? [Reminder] else {
            fatalError("Wrong data type: value must be a Reminder object; received \(type(of: value))")
        }
        return super.reverseTransformedValue(reminder)
    }
}



extension NSValueTransformerName {
    static let reminderToDataTransformer = NSValueTransformerName(rawValue: "ReminderToDataTransformer")
}

我在初始化NSPersistantContainer之前使用下面的代码注册了ReminderDataTransformer

ValueTransformer.setValueTransformer(ReminderDataTransformer(), forName: .reminderToDataTransformer)

我在 xCode 的数据模型检查器中使用 ReminderToDataTransformer 作为转换器。


但是保存实体时出现如下错误,无法正常工作

 [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x282ec0780> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null)
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x282ec0780> , <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo of (null)
2020-12-31 21:44:09.300394+0100 ReminderApp[26406:6247995] [error] error: -executeRequest: encountered exception = <shared NSSecureUnarchiveFromData transformer> threw while encoding a value. with userInfo = (null)

更新

也不例外。第二次启动应用程序时,此错误记录在控制台中。

[error] fault: exception raised during multi-threaded fetch <shared NSSecureUnarchiveFromData transformer> threw while decoding a value. ({
    NSUnderlyingError = "Error Domain=NSCocoaErrorDomain Code=4864 \"value for key 'root' was of unexpected class 'NSArray (0x1fa392238) [/System/Library/Frameworks/CoreFoundation.framework]'. Allowed classes are '{(\n    \"Reminder (0x100fb6920) [/private/var/containers/Bundle/Application/306C3F0B-75AA-4A2D-A934-260B2EB63313/ReminderApp]\”\n)}’.\” UserInfo={NSDebugDescription=value for key 'root' was of unexpected class 'NSArray (0x1fa392238) [/System/Library/Frameworks/CoreFoundation.framework]'. 

我想我无法正确编码/解码 Reminder 的数组,因为如果我将代码更改为存储 Reminder 而不是 [Reminder]

它会起作用

明确一点,我可以存储 Reminder,但不能存储 [Reminder]


如何将 [Reminder] 存储为 Transformable


如果您要取消归档数组,则必须将 NSArray 添加到顶层 classes,这就是我对错误消息的理解

override class var allowedTopLevelClasses: [AnyClass] {
    return [NSArray.self, Reminder.self]
}

顺便说一下,考虑将数组编码为 JSON 并将其保存为简单的字符串,而不是可转换的。可以通过计算的 属性.

执行转换

class 可以是代码少得多的结构

public struct Reminder : Codable {
    public var date: Date
    public var isOn: Bool
}

NSManagedObject子class中创建一个String属性

@NSManaged public var cdReminders : String

和计算的 属性

var reminders : [Reminder] {
    get {
       return (try? JSONDecoder().decode([Reminder].self, from: Data(cdReminders.utf8))) ?? []
    }
    set {
       do {
           let reminderData = try JSONEncoder().encode(newValue)
           cdReminders = String(data: reminderData, encoding:.utf8)!
       } catch { cdReminders = "" }
    }
}

添加到@vadian 的回答中,如果您想包含来自父数据转换器的允许的顶级 类,请尝试

override static var allowedTopLevelClasses: [AnyClass] {
    var allowed = super.allowedTopLevelClasses
    allowed(contentsOf: [Reminder.self])
    
    return allowed
}