CoreData to-Many relationship saving NSSet relationship property

I have an ShoppingItem Entity(attributes: name, id, unit, qty, description) and another entity ShoppingList(attributes: listDate, listName) and a relationship property : items which is many-to-many relationship.

The use case is : _The items that are selected by the user have to be updated to the list on the particular date.

let myList = GroceryList(context: CoreDataManager.shared.viewContext)
    myList.name = "One more List"
    myList.madeOn = Date()
1.     myList.mutableSetValue(forKey: "groceryItems").add(selectedGroceryItems)

    CoreDataManager.shared.save()

selectedGroceryItems is of type

struct ItemEntityViewModel {
   
  let groceryItem: GroceryItem
   
  var itemEntityid: NSManagedObjectID {
    return groceryItem.objectID
  }
   
  var id: UUID {
    return groceryItem.id ?? UUID()
  }
  var name: String {
    return groceryItem.name ?? ""
  }
   
  var category: String {
    return groceryItem.category ?? "Not available"
  }
   
  var unit: String? {
    return groceryItem.unit ?? ""
  }
   
  var qty: Double? {
    return Double(groceryItem.qty)
  }
}

line 1 throws exception as follows:

NSInvalidArgumentException', reason: -[Swift.__SwiftDeferredNSArray entity]: unrecognized selector sent to instance 0x600003f5e320' terminating with uncaught exception of type NSException

Do you mean this line ?

    myList.mutableSetValue(forKey: "groceryItems").add(selectedGroceryItems)

Without more context information (what is selectedGroceryItems for instance ?), you should check:

  • "groceryItems" is a valid key in your CoreData
  • selectedGroceryItems is of appropriate class for adding to the set

This is the ER model

You may want to try changing

myList.mutableSetValue(forKey: "groceryItems").add(selectedGroceryItems)

to

myList.addToGroceryItems(selectedGroceryItems)

which is a method that should have been synthesized for you based on your Core Data model.

Just type myList.add and pick from Xcode's autocomplete.

CoreData to-Many relationship saving NSSet relationship property
 
 
Q