0
votes

I am new to CoreData and apologize in advance if the question is difficult to understand. So... Assuming we have two entities - Cars and Items (one to many relationship). I have 2 objects in cars (let§s say... BMW and Audi) and want to add a new item to Audi. How to select the Audi entity in which to add new item object? I know how to add new instance of item, but how to associate them to the specific entity... let say of Audi?

let entity = NSEntityDescription.entity(forEntityName: "Cars", in: context)
let newItem = NSManagedObject(entity: entity!, insertInto: context) as! Item
newItem.type = "Oil"
1

1 Answers

0
votes

The Item entity should have a relationship for the car it belongs to. To set the car that the item belongs to, set the variable for the car in the relationship, something similar to the following:

newItem.car = selectedCar // The Audi in your example.

Your app's interface has a table view or some other view to select cars. When someone selects a car from the list, store the selected car in a variable and use that to set the item's car.

Without more information about your Car and Item entities and your app's user interface, I cannot provide a more detailed answer.