Hello. I've wrestled with this for four days without success so I could use some help. The code below simply adds a new record to an Entity ('Activity'). This code works fine and does what it is supposed to on add and delete. However, the entity now has a relationship from itself (Activity) to another Entity (Player). Each Activity has 1 player. The view is loaded on init with the currently active player and that record is stored in a state variable. Now when the viewcontext is saved, the record stored in the state variable (a Player record is invalidated). This physically is seen as the players name disappears from the screen after the context save. This ONLY happens when the relationship field is maintained - if I don't do that, the activity record saves fine and the state is maintained. I cant figure this out and could use help.
Code
Code - https://developer.apple.com/forums/content/attachment/4dacbb10-3312-4af9-96d5-d83c150fc298
Post
Replies
Boosts
Views
Activity
I've been working this problem for a couple of days and decided to ask for help. The use case is that I have two Core Data Entities (in CloudKit) which have a relationship between them. In the updating of one entity, I am trying to add the related entity by adding the result from a user selection, via a picker.
The issue I am facing is that I can't get the picker to return the record as the selection - it's always null. I have developed the following test code to highlight the specific case. The picker populates and I can make it return anything other than the actual record - but to insert in the relationship, I need the record itself. Here is the picker test code. Selection is ALWAYS empty.
I would appreciate direction.
Craig
struct TestView: View {
@Environment(\.managedObjectContext) var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Player.familyName, ascending: true)],
animation: .default)
private var players: FetchedResultsPlayer
@State var selection: Player?
var body: some View {
VStack{
Picker("", selection: $selection){
ForEach(players, id: \.self){ (player: Player) in
Text(player.givenName!).tag(player.self)
}
}
Text(((selection?.familyName ?? "default")))
Text("\(players.count)")
}
}
}