TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How to make SwiftData document-based app coexist with Core Data using same persistent container from the document

Forums > SwiftUI

I am working on a SwiftData document-based app. Most things were progressing pretty well until I tried to build more complicated predicates; specifically the lack of NSCompoundPredicate-like support in SwiftData. I have been trying to incorporate Core Data to coexists in my app so I can use FetchRequest when I need complicated predicates. There isn't a lot of information available. I have looked at Apple documentations, WWDC videos, HackingWithSwift, SO, etc.

If you know how I can get a NSManagedObjectContext from the SwiftData document modelContext in my app, please advice.

My simplified App code is below:

  @main
struct MyApp: App {

  var body: some Scene {
      DocumentGroup(editing: .myAppDocument, migrationPlan: MyAppMigrationPlan.self) {
          MainWindowView()
      }
  }
}

extension UTType {
  static var myAppDocument: UTType {
      UTType(importedAs: "com.example.myApp")
  }
}

struct MYAppMigrationPlan: SchemaMigrationPlan {
  static var schemas: [VersionedSchema.Type] = [
      MYAppVersionedSchema.self,
  ]

  static var stages: [MigrationStage] = [
      // Stages of migration between VersionedSchema, if required.
  ]
}

struct MyAppVersionedSchema: VersionedSchema {
  static var versionIdentifier = Schema.Version(1, 0, 0)

  static var models: [any PersistentModel.Type] = [
      Entry.self, Tag.self, Collection.self
  ]
}

So I would like to get a NSManagedObjectContext with the same persistent container as the SwiftData document. I think the place to do it is in MainWindowView(). But I am at a lost on how to make it happen. I have tried looking into view global environment objects like documentConfiguration, modelContext, and managedObjectContext but failed to make the managedObjectContext share the same container as modelContext.

Any info/hint is greatly appreciated. Thank you for reading.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.