lundi 29 décembre 2014

Link CoreData entities from JSON initialization

I have a simple question about CoreData. I'm developing an application in Swift where I query a distant API which returns JSON data. The response is serialized from string to Dictionary on my side.


I have multiple entities in a Core Data model with relationships between them.


When getting a response from the API I create an object (subclass of a NSManagedObject) with a custom initializer taking the Dictionary.


Here is a simplified example:



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)
}
}


My question is about the Type element. There is a fix number of types ("Dance", "Jazz", ...) on the server side, hence I'd like to also have a fix number of types in my Core Data. However, with my current implementation it will create a new Type entity each time I create a Song object. So what I'd like is some sort of "foreign key" association between the two (even though CoreData is not a database per se...)


What's the best way to achieve this knowing that Type has an id property which uniquely identifies it on the server? Or should I really not care about such things when using Core Data?




Aucun commentaire:

Enregistrer un commentaire