davidethell davidethell - 1 year ago 118
Swift Question

I can't use my core data model in two targets in a Swift project

The class name for entity models in the Core Data model has to have the app name prepended to it. So for an entity named User the class name in the model editor has to be MyAppName.User. This works fine until I added a second target to my project.

The new project expects the entity class names to be SecondAppTargetName.User. How do we support two targets using the same core data model? I tried prepending ${PRODUCT_NAME}.User instead, not expecting it to work. And it doesn't work.

Any ideas on how to share one core data model between targets and satisfy the need of Swift projects to have the PRODUCT_NAME prepended to the class in the model editor?

It appears from the Apple documentation here that adding the module name as a prefix to the class name in the model entity inspector is the preferred behavior. If so this seems like a gaping hole since it precludes multiple targets using the same data model. I still have found no workaround for this yet. Some posts here on SO have indicated that using @objc(ClassName) in front of the Swift class definition for the managed object will do the trick, but I haven't been able to verify that yet.

Answer Source

It turns out that the answer does appear to be adding the @objc(ClassName) directive above the class definition in the Swift file as noted in this StackOverflow answer about a related problem. At least it is the answer at this stage with XCode 6 beta 5.

So for an entity class called User you would need:

class User: NSManagedObject {

I have tested this in a two-target project and removed all the prefixes from the model entity inspector and it works. I'm wondering why Apple would include the prefix requirement in their documentation since it imposes a restraint on multiple targets using the same core data model. It appears the @objc fix is the proper solution or maybe just a temporary solution during this beta stage.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download