Adding Core Data to a Swift Package
Last year, when Swift Package Manager added support for Xcode and iOS projects was announced, I was overjoyed. A short time later, I realized that package resources weren’t supported and many of my hope and dreams for using it were immediately dashed. Thankfully, early this year SE-0271 was approved and resource support for Swift Package Manger was imminent. June 22, Xcode 12 was finally available to developers (in beta form of course). Swift Packages weren’t the first thing I dove into and they didn’t make it into week one of my exploration. This week though, I’m going SPM wild and as a part of that endeavor, I have a project whose Code Data Model I wanted to move into a Swift Package. In case anyone else is interested in doing the same thing, I decided to write this brief guide. This post is meant to be a quick and dirty guide to putting your Core Data Model into a Swift Package and assumes familiarity with Core Data and that you already have an existing Core Data data model in a project.
1) Begin by creating a new Swift Package.
For now we’ll add the Swift Package to our Existing Project.
2) The next step is to drag your Core Data model into the package under the Sources folder.
3) Herein lies the magic
Create or use an existing file that contains a class that will be used to manage the setup of the Core Data stack. Make sure that this file is also in the Sources folder of your Swift Package. This file needs to contain the following two items:
1. A custom subclass of NSPersistentStoreContainer. This subclass can be empty, but it must exist for the Swift Package magic to work.
2. A persistent container that conforms to your custom subclass. Within the setup for that container, explicitly load the model and reference Bundle.module
as the location for the model file.
Now that that Package is set up you can either use it as a local resource by manually importing the library into targets or by distributing it online. Either way remembers to import your new Package anywhere that references your Core Data model or any of its NSManagedObject subclasses.
Here are some helpful resources:
Core Data Best Practices - WWDC18