如何在使用coredata NSManagedObject进行映射时对swift4可编码的NSOrderedSet变量进行编码/解码?
import CoreData
import Foundation
@objc(TestObject)
public class TestObject:NSManagedObject,Encodable
{
@nonobjc public class func fetchRequest() -> NSFetchRequest<TestObject> {
return NSFetchRequest<TestObject>(entityName: "TestObject")
}
@NSManaged public var testName: String?
@NSManaged public var devices: NSOrderedSet? // of entity type "Device"
enum CodingKeys: String, CodingKey {
case testName
case devices
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy:CodingKeys.self)
try container.encode(testName,forKey:.testName)
try container.encode(devices,forKey:.devices)
}
}
public required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
try container.decode(testName,forKey:.testName)
try container.decode(devices,forKey:.devices)
}
它给出了错误: 编译器给出了这个错误
No 'decode' candidates produce the expected contextual result type 'NSOrderedSet?'
答案 0 :(得分:3)
您可以利用自动生成的访问器之一来做到这一点。
//addToDevices(_ value: Device)
public required convenience init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.testName = try container.decode(String.self, forKey: .testName)
let devices = try container.decode([Device].self, forKey:.devices)
devices.forEach { self.addToDevices($0) }
}
如果您没有自动生成的访问器,请执行以下步骤
答案 1 :(得分:0)
这是因为,NSOrderedSet
不支持Codable
协议。而是尝试使用Set
。
@NSManaged public var devices: Set<String>?
无论您的应用支持什么,都可以创建Set
数据类型。