
Above is my data model diagram.
Everytime i create a Car whcih contains a model and make, it adds a car object to core data.
The problem is that it also adds 1 make and 1 model to the core data, so i get duplicates.
for example, in the following code, it saves 1 car object 2 models, and 2 makes,
so I get a duplicate Make in my table (2 “Nissan”).
How can i avoid this? is it possible to create primary keys?
In the following example i want to assume that make and models already exists, and a car is only referencing to them, so how can I avoid inserting into make, and model, and only insert into car?
- (void)MyCode
{
[self AddCar:@"Nissan" @"Rogue"];
[self AddCar:@"Nissan" @"Murano"];
}
- (void)AddCar :(NSString*)_make :(NSString*)_model
{
Car *car = [[Car alloc] initWithEntity:[NSEntityDescription entityForName:@"Car"
inManagedObjectContext:self.managedObjectContext]
insertIntoManagedObjectContext:self.managedObjectContext];
Make *make = [[Make alloc] initWithEntity:[NSEntityDescription entityForName:@"Make"
inManagedObjectContext:self.managedObjectContext]
insertIntoManagedObjectContext:self.managedObjectContext];
make.name = _make;
Model *model = [[Model alloc] initWithEntity:[NSEntityDescription entityForName:@"Model"
inManagedObjectContext:self.managedObjectContext]
insertIntoManagedObjectContext:self.managedObjectContext];
model.name = _model;
car.make = make;
car.model = model;
[self saveContext];
}
There are a few issues here.
The data model shows that the
MakeandModelentities each have a to-one relationship withCar. Therefore, there can be only oneCarfor eachMakeand only oneCarfor eachModel. In other words, given that data model, Nissan can only make oneCar. You probably want a to-manycarsrelationship inModelso that Nissan can make more than oneCar. Same thing withMakeso that there can be more than oneCarwith a givenMake.The way
NSManagedObjects are inserted into the managed object context is incorrect. It should be done like this:Finally, your code shows that a new
MakeandModelentity are created for eachCar. If you are starting with the name of aMake, you probably want to search the managed object context for aMakethat has a matching name. If found, just set themakerelationship of the newCarto theMakeentity that is already in the context. If not found, create a newMakeentity and set up a relationship to that.