How do I save a Todo item and set its relationship to an existing Category if one already exists? I know how to create a new Category and set its relationship to the new Todo already as shown below. I'm doing this within a form.
Category
is set to have many
Todos
.
let category2 = Category(context: viewContext)
category2.id = UUID()
category2.title = "Fun"
let todo = Todo(context: viewContext)
todo.title = "Hi"
todo.dueDate = Date.now
todo.relationship = category2
try? viewContext.save()
//todo.relationship = create a new Category if one doesn't exist, if it does exist, select that as the relationship. If no category, then do nothing
I have been following this solution here
CodePudding user response:
My code was fine I was just missing the merge policy which is explained here. If you are following along with Paul's HackingWithSwift videos make sure you do this...
This will handle duplicates along with the constraint set for the core data entity.
self.container.viewContext.mergePolicy = NSMergePolicy.mergeByPropertyObjectTrump