How to use Core Data’s ManagedObjectModel inside a framework?

I’m a bit late for flohei’s issue, but hopefully this helps anybody else who wanders by. It is possible to get this to work without having to perform script-fu to copy resources around!

By default Apple’s Core Data template gives you something like this:

lazy var managedObjectModel: NSManagedObjectModel = {
  let modelURL = NSBundle.mainBundle().URLForResource("MyCoreDataModel", withExtension: "momd")!
  return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

That would load your Core Data resources out of the main bundle. The key thing here is: if the Core Data model is loaded in a framework, the .momd file is in that framework’s bundle. So instead we just do this:

lazy var managedObjectModel: NSManagedObjectModel = {
    let frameworkBundleIdentifier = "com.myorg.myframework"
    let customKitBundle = NSBundle(identifier: frameworkBundleIdentifier)!
    let modelURL = customKitBundle.URLForResource("MyCoreDataModel", withExtension: "momd")!
    return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

That should get you up and running.

Credit: https://www.andrewcbancroft.com/2015/08/25/sharing-a-core-data-model-with-a-swift-framework/

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)