Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.

2016-06-23

Using a datamodel with multiple targets

Recently I stumbled across a problem where I wanted to use a single datamodel for two targets.

While the first target had successfully used a datamodel, when I added the model to a second target I went through a succession of error messages:

+entityForName: could not locate an entity named 'SwiftfireStatistics.CDClients' in this model.

CoreData: warning: Unable to load class named 'Swiftfire.CDClients' for entity 'CDClients'

NSFetchRequest could not locate an NSEntityDescription for entity name 'SwiftfireStatistics.CDClients'

The problem seemed hard to pin down, and was badly reproducible. WTH was going on? While there was an answer on StackOverflow that helped, (adding @objC(<name>)) it was not satisfactory and I wanted to know what the underlying problems was.

I learned quite a bit about how a datamodel works and how namespaces are used, but in the end the solutions was as simple as unsatisfactory:

In the operations

let fetchRequest = NSFetchRequest(entityName: CDClients.className())

and

NSEntityDescription.insertNewObjectForEntityForName(CDClients.className(), inManagedObjectContext: self.managedObjectContext) as! CDClients

I was simply trying to be too clever for my own good.

The usage of CDClients.className() turned out to be the culprit. A class name has a namespace added in front. Thus the className() of a core data class CDClients in the target SwiftfireStatistics is in full "SwiftfireStatistics.CDClients".

What the core data functions really want is the class name without the preceding namespace:

let fetchRequest = NSFetchRequest(entityName: "CDClients")
NSEntityDescription.insertNewObjectForEntityForName("CDClients", inManagedObjectContext: self.managedObjectContext) as! CDClients

I don't like that, but it is the way it is. We could introduce a "name" property of type string and use that property instead, but...

Oh well, its the way it is.

Happy coding...

PS: You may also be interested in "Moving a datamodel from one project to another"

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

No comments:

Post a Comment