CoreData in SPM Package

I've developed an SPM module in which I have a CoreData model defined as a xcdatamodeld file and I'm having trouble executing tests from the command line, which I want for a CI integration.

In the package I load the model by constructing a URL using Bundle.module.url(forResource: "ModelName", withExtension: "momd"). This works when building and testing in Xcode.

When executing commands such as swift test from the terminal however, it doesn't, as Bundle.module.url(forResource:withExtension) fails to find the file. Comparing the build artifacts between Xcode's DerivedData and SPM's .build I see that both produce a PackageName_PackageName.bundle but while the Xcode version contains a momd file the SPM version contains an unprocessed xcdatamodeld file.

I've tried adding the xcdatamodeld as an explicit resource in the Package.swift file such that the package target now includes resources: [.process("Resources/ModelName.xcdatamodeld")] as an argument. This does not impact the Bundle output.

Any ideas how I can address this to be able to execute unit tests via the command line?

Historically I suppose the solution would be to use generate-xcodeproj but my understanding is that that has been deprecated and executing it via Xcode 14.2 fails due to a missing toolchain tool.

Answered by Zeppin in 747509022

A (somewhat brittle) solution for anyone that finds this via Google.

After running a build with swift build I manually invoke the momc compiler to produce the necessary momd and save it to the SPM generated bundle. After that I execute the tests.

  1. swift build
  2. /Applications/Xcode.app/Contents/Developer/usr/bin/momc Sources/PackageName/Resources/ModelName.xcdatamodeld .build/arm64-apple-macosx/debug/PackageName_PackageName.bundle/ModelName.momd
  3. swift test
Accepted Answer

A (somewhat brittle) solution for anyone that finds this via Google.

After running a build with swift build I manually invoke the momc compiler to produce the necessary momd and save it to the SPM generated bundle. After that I execute the tests.

  1. swift build
  2. /Applications/Xcode.app/Contents/Developer/usr/bin/momc Sources/PackageName/Resources/ModelName.xcdatamodeld .build/arm64-apple-macosx/debug/PackageName_PackageName.bundle/ModelName.momd
  3. swift test
CoreData in SPM Package
 
 
Q