【发布时间】:2014-12-30 02:16:49
【问题描述】:
我有一个关于 CoreData 的简单问题。我正在用 Swift 开发一个应用程序,我在其中查询一个返回 JSON 数据的远程 API。响应从字符串序列化到我这边的字典。
我在 Core Data 模型中有多个实体,它们之间存在关系。
当从 API 获得响应时,我创建了一个对象(NSManagedObject 的子类),其中包含一个使用字典的自定义初始化程序。
这是一个简化的例子:
class Song: NSManagedObject {
@NSManaged var type : Type?
@NSManaged var name : String?
override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
init(fromDictionary dictionary: NSDictionary, context: NSManagedObjectContext, filterRemoved: Bool) {
let entity = NSEntityDescription.entityForName("Song", inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
if let nameValue = dictionary["name"] as? String{
name = nameValue
}
if let typeData = dictionary["type"] as? NSDictionary{
type = Type(fromDictionary: typeData, context:context)
}
}
我的问题是关于 Type 元素。服务器端有固定数量的类型(“Dance”、“Jazz”...),因此我想在我的核心数据中也有固定数量的类型。但是,在我当前的实现中,每次创建 Song 对象时都会创建一个新的 Type 实体。所以我想要的是两者之间的某种“外键”关联(即使 CoreData 本身不是数据库......)
知道 Type 具有在服务器上唯一标识它的 id 属性,实现此目的的最佳方法是什么?还是我在使用 Core Data 时真的不应该关心这些事情?
【问题讨论】: