Say, I have 2 Entities: GameLevel and UserResult.
The GameLevel is fetched from my Server and stored locally in Core Data. And UserResult - is the result of the user playing this level (date when played, score, etc), it's created by the user and stored in Core Data too.
UserResult is then backed up to the user's private CloudKit with NSPersistentCloudKitContainer. I'm doing this with two different Core Data Configurations.
That's why I can't have a standard Core Data relationship between them. Right now, the UserResult has a field levelId, that stores the GameLevel's id.
What is the correct way to fetch both Entities and use them both to display in a View?
Here is how I fetch the GameLevel:
import SwiftUI
import CoreData
struct MainView: View {
@FetchRequest private var levels: FetchedResults<GameLevelEntity>
init() {
let request: NSFetchRequest<GameLevelEntity> = GameLevelEntity.fetchRequest()
request.sortDescriptors = [NSSortDescriptor(keyPath: \GameLevelEntity.publishedDate, ascending: false)]
request.fetchLimit = 5
_levels = FetchRequest(fetchRequest: request)
}
var body: some View {
// HERE:
// I would like to display GameLevel data combined with UserResult data:
ForEach(levels) { level in
//Doesn't really matter
Text(level.title)
}
}
}
So I need to make a second @FetchRequest based on the levelIds from the first @FetchRequest. I know I can probably do that with a predicate:
let predicate = NSPredicate(format: "levelId IN %@", previouslyFetchedLevelIds)
But how to do that in SwiftUI?