swiftcore-datacocoapodsnsentitydescription

Cocoa pod with Core Data can not find entity in consuming app


I've created a framework that's a cocoapod, the framework uses core data, my pod spec has:

s.resource_bundles = {
  'FrameworkModel' => ['Model/**/*.xcdatamodeld']
  }

and everything works fine in a demo app that's a different target in the framework work space, however when I install it as a pod I got an

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'NSFetchRequest could not locate an NSEntityDescription for entity name 'EntityName''

I'm not quite sure what to try but I did change the module name on the data model file with no effect. (I went from the name of the framework project to 'Current Product Module' and back.

I do see the data model file in the pods project in the workspace.


Solution

  • My problem was caused by how I created my core data stack, specifically the managed object model, which I was creating from a URL from a bundle that doesn't exist as a pod consumer, so now it's in definition I check if a bundle is available as it would be in the workspace (for the demo app), or if it exists under the name of the resource bundle defined in my pod file, like this:

    fileprivate lazy var managedObjectModel: NSManagedObjectModel = {
    
    // the moc's model should be accessible via apps in this workspace
    // or through the module that cocoapods will create as part of the file's
    // resource bundle, as such, we need to look in two different places
    // to use the correct bundle at run time
    var rawBundle: Bundle? {
    
        if let bundle = Bundle(identifier: "com.thefredelement.Framework") {
            return bundle
        }
    
        guard
            let resourceBundleURL = Bundle(for: type(of: self)).url(forResource: "FrameworkModel", withExtension: "bundle"),
            let realBundle = Bundle(url: resourceBundleURL) else {
                return nil
        }
    
        return realBundle
    }
    
    guard let bundle = rawBundle else {
        print("Could not get bundle that contains the model ")
        return NSManagedObjectModel()
    }
    
    guard
        let modelURL = bundle.url(forResource: self.model, withExtension: "momd"),
        let model = NSManagedObjectModel(contentsOf: modelURL) else {
            print("Could not get bundle for managed object model")
            return NSManagedObjectModel()
    }
    
    return model
    }()