我试图让一个简单的NSManagedObject类符合Encodable,这样我就可以轻松地将它编码为JSON。
我有一个名为TestObject的实体,它与名为Device的实体有一对多的关系。
一切正常,直到我尝试编码NSSet(与许多关系)。
import UIKit
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: NSSet? // 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)
}
}
我从编译器收到的错误是
reference to member 'devices' cannot be resolved without a contextual type
try container.encode(devices,forKey:.devices)
这个编译器告诉我什么,我如何编码我的对象及其关系?