我有一个应用,其中核心数据是模型层。此外,还可以通过API更新数据。核心数据模型包含Rim:Component和Hub:Component,其中Component是Rim和Hub的抽象父实体。我该如何初始化超类组件,使其在其初始值设定项中具有Rim和Hub的通用属性(例如下面示例中的// API对象)?
NSManagedObject伤了我的头:-) 这是我要实现的示例:
// API objects
protocol APIObject {
init?(jsonObject: [String: AnyObject])
}
class APIComponentObject: APIObject {
var manufacturer: String
var model: String
required init?(jsonObject: [String: AnyObject]) {
guard let manufacturer = jsonObject["manufacturer"] as? String else { return nil }
guard let model = jsonObject["model"] as? String else { return nil }
self.manufacturer = manufacturer
self.model = model
}
}
class APIRimObject: APIComponentObject {
var sizes: [String: Double]
required init?(jsonObject: [String: AnyObject]) {
guard let sizes = jsonObject["sizes"] as? [String: Double] else { return nil }
self.sizes = sizes
super.init(jsonObject: jsonObject)
}
}
class APIHubObject: APIComponentObject {
var old: Double
required init?(jsonObject: [String: AnyObject]) {
guard let old = jsonObject["old"] as? Double else { return nil }
self.old = old
super.init(jsonObject: jsonObject)
}
}
// CoreData objects
class Component: NSManagedObject {
@NSManaged var manufacturer: String
@NSManaged var model: String
convenience init(apiComponentObject: APIComponentObject, entity: NSEntityDescription, context: NSManagedObjectContext) {
self.init(entity: entity, insertInto: context)
manufacturer = apiComponentObject.manufacturer
model = apiComponentObject.model
}
}
class Rim: Component {
@NSManaged var sizes: [String: Double]
convenience init(apiRimObject: APIRimObject, entity: NSEntityDescription, context: NSManagedObjectContext) {
self.init(entity: entity, insertInto: context)
//super.init(apiComponentObject: apiRimObject, entity: entity, context: context)
sizes = apiRimObject.sizes
}
}
class Hub: Component {
@NSManaged var old: Double
convenience init(apiHubObject: APIHubObject, entity: NSEntityDescription, context: NSManagedObjectContext) {
self.init(entity: entity, insertInto: context)
//super.init(apiComponentObject: apiHubObject, entity: entity, context: context)
old = apiHubObject.old
}
}