Reputation: 505
I'm trying to follow the information on How to Deal with Temporary NSManagedObject instances?.
For my data model I have an entity which has a has many relationship to entity2.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
NSEntityDescription *priceEntity = [NSEntityDescription entityForName:@"Price" inManagedObjectContext:self.managedObjectContext];
Product *product = [[Product alloc]initWithEntity:entity insertIntoManagedObjectContext:nil];
Price *price = [[Price alloc]initWithEntity:priceEntity insertIntoManagedObjectContext:nil];
product.name = @"some product";
price.name = @"some price";
NSError *error;
[product addPricesObject:price];
[self.managedObjectContext insertObject:product];
if(![self.managedObjectContext save:&error])
{
NSLog(@"%@",error.localizedDescription);
}
I get an error from the save method which logs "The operation couldn’t be completed. (Cocoa error 1550.)"
Without the setting up the relationship the code seems to work fine. Is there an issue with my code or is there a problem with relationships when using the answer in the stackoverflow page?
Thank You
Upvotes: 0
Views: 158
Reputation: 1
I have the same problem, and I solved it.
try this:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:self.managedObjectContext];
NSEntityDescription *priceEntity = [NSEntityDescription entityForName:@"Price" inManagedObjectContext:self.managedObjectContext];
Product *product = [[Product alloc]initWithEntity:entity insertIntoManagedObjectContext:nil];
Price *price = [[Price alloc]initWithEntity:priceEntity insertIntoManagedObjectContext:nil];
product.name = @"some product";
price.name = @"some price";
//first:insert to managedObjectContext (all managedObject!)
[self.managedObjectContext insertObject:product];
[self.managedObjectContext insertObject:price];
//second:add relationship
[product addPricesObject:price];
NSError *error;
if(![self.managedObjectContext save:&error])
{
NSLog(@"%@",error.localizedDescription);
}
Upvotes: 0
Reputation: 539685
You have added product
to the managed object context, but not the related price
.
You should add:
[self.managedObjectContext insertObject:price];
before saving the context.
Upvotes: 1