使实体关系可编码/可解码时出错

时间:2018-06-07 07:14:20

标签: core-data swift4 codable decodable encodable

如何在使用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?'

2 个答案:

答案 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. 选择您的项目数据模型文件
  2. 在菜单栏上,从Apple左侧的第7号选择“编辑器”
  3. 选择“创建NSManagedObject子类
  4. 选中数据模型旁边的框
  5. 选中您要使用的实体的框
  6. 选择“创建”

答案 1 :(得分:0)

这是因为,NSOrderedSet不支持Codable协议。而是尝试使用Set

@NSManaged public var devices: Set<String>? 

无论您的应用支持什么,都可以创建Set数据类型。