Search code examples
iosswiftcore-data

Assign array of items to selected item - Many to Many relationship in core data


I'm working on an iOS app with Core Data and Swift 5.5 I have 2 entities ( Category ) and ( Item ) and I created a Many-to-Many relationship between those entities, so in Category, it has ( items ) and in Item, it has ( categories ).

now I want to assign multiple items to selected Categrory so I tried this code but it didn't work

var selectedItems = [Item]()

let category = selectedCategory
category.items = selectedItems

do {
  try moc.save()
} catch {
  print(error.localizedDescription)
}

This way working well in One-To-Many relationships but in Many-To-Many it didn't work. So how I can fix this issue or how I can assign an array of selected items to a specific category?


Solution

  • Instead of writing to the property you should use one of the generated add (or remove) methods. If the relationship is named items you should have two method addToItems for adding a single or multiple Item

    So try

     category.addToItems(NSSet(array: selectedItems))