Search code examples
swiftxcodeswift-package-manager

CoreData Model within Swift Package


I am trying to put a CoreData model into a Swift Package to extract my model code / classes from my main codebase.

I have done the following to recreate the issue I'm having from scratch:

  • Create a new swift package called SampleModelPackage (File -> New -> Swift Package)
  • Created a Core Data Model Definition File (Create File -> New -> File | iOS -> Core Data -> Data Model)
  • Saved it in the Sources/SampleModelPackage directory alongside the auto-generated SampleModelPackage.swift

Now - when I attempt to open the Model.xcdatamodelId file in Xcode, it just shows me a "Version" icon (see screenshot), whereas creating a Core Data Model file in a Project or Framework will allow me to edit the model.

The second / follow up question would be how would I then extend the code-gem'd model files as normal? And how would I load that model definition (normally I would use a Bundle ID and the model file name)

I have tried adding the model file to the resources array of the Package.swift file (using .process and using .copy) as described on this page: https://developer.apple.com/documentation/swift_packages/bundling_resources_with_a_swift_package

Or more generally, is this even possible? (this article https://ishabazz.dev/blog/2020/7/5/using-core-data-with-swift-package-manager seems to imply that packaging core data models like this is possible)

(I am using Xcode 12.4)

Exhibit A


Solution

  • You need to create your Core Data model in an ordinary Xcode project, then you can create your package and drag the model to it. (This is also what was done in the linked article if you look carefully even though it was not clearly described).

    I believe the the best thing is to manually generate the source code files for your entities and add them to your package. You load the model using Bundle but instead of Bundle.main you use Bundle.module