UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.