title: Deleting object from one to many relationship in Core Data
body: <p>I currently have a problem deleting an object in a to many relationship. </p>
  
  <p>My app have the following relationship: </p>
  
  <p>Product &lt;&lt;- Cart </p>
  
  <p>When the user pushes a "add to cart" button in my viewcontroller, the following code is setting the relations between the product object and the cart</p>
  
  <pre><code>    + (Cart *)addProductToCartWithProduct:(Product *)product inManagedObjectContext:(NSManagedObjectContext *)context {
  
      Cart *cart = nil;
  
      NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Cart"];
  
      NSError *error = nil;
      NSArray *carts = [context executeFetchRequest:request error:&amp;error];
  
      if (!carts || ([carts count] &gt; 1)) {
          // handle error
      } else if (![carts count]) {
          cart = [NSEntityDescription insertNewObjectForEntityForName:@"Cart" inManagedObjectContext:context];
  
  
      } else { // they already have a cart started
          cart = [carts lastObject];
      }
      /*Get Object ID to safely pass NSMangedObject between threads (A background worker thread and the main thread). */
        NSManagedObjectID *retID = [product objectID];
      [cart addProductsObject:(Product *)[context objectWithID:retID]];
  
  //Inverse relationship
      [(Product *) [context objectWithID:retID] setInCart:cart];
  
  
       return cart;
  }
  </code></pre>
  
  <p>This then returns a cart object, which I pass to my cart viewcontroller, and fetch the products in that relationship like so: </p>
  
  <pre><code>             // Fetch request for "Product":
  NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Product"];
  
  // Fetch only products for the cart:
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"inCart = %@", self.cart];
  [fetchRequest setPredicate:predicate]; 
  
  
  NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"navn" ascending:YES];
  [fetchRequest setSortDescriptors:@[sortDescriptor]];
  
  self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_theManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
  _fetchedResultsController.delegate = self;
  </code></pre>
  
  <p>When I then try to delete an object from the relationship like so: </p>
  
  <pre><code>-(void)RemoveFromCart:(UIButton *)sender {
  
       NSIndexPath *ip = [NSIndexPath indexPathForRow:sender.tag inSection:0];
  
      Product *prod = (Product *)[self.fetchedResultsController objectAtIndexPath:ip];
  
  
  
         prod.inCart = nil;
         [_cart removeProductsObject:prod];
  
  
      NSLog(@"Cart %@ %@", _cart.products, prod);
  
  
      [self saveCurrentContext:_theManagedObjectContext];
  
  
  
  
      [self loadCart]; 
      [_orderTable reloadData];
  
  
  }
  </code></pre>
  
  <p>The product is removed visually (gone from the tableview/screen) because inCart is set to nil, but not technically... when I log the cart object, the product object is still in the relationship, so it seems like the <code>[_cart removeProductsObject:prod];</code> is not working. </p>
  
  <p>And it also doesn't work the other way around, when I try to add the same product to the cart, I just have deleted (from the cart), for some reason the inverse relationship "inCart" is not set, after I have set it to "nil", when the product object is removed. </p>
  
  <p>Why is this happening? and how do I fix it? :). </p>
  
  <p>EDIT: </p>
  
  <p>Pictures showcasing inverse relationships in Core data model editor: </p>
  
  <p><img src="https://i.stack.imgur.com/xfHE2.png" alt="enter image description here"></p>
  
  <p><img src="https://i.stack.imgur.com/VCWVl.png" alt="enter image description here"></p>
  
  <p>Pass Cart to other viewcontroller: </p>
  
  <pre><code>[[[DataManager sharedInstance] backgroundManagedObjectContext] performBlock:^{
  
  
      UITabBarController *tabBarController = self.tabBarController; 
  
      for (UINavigationController *navController in  tabBarController.viewControllers) {
  
  
          for (UIViewController *vc in navController.viewControllers) {
              if ([vc isMemberOfClass:NSClassFromString(@"CartViewController")]){ 
                 CartViewController *cartVC = (CartViewController *) vc;
                  cartVC.cart = [Cart addProductToCartWithProduct:prod inManagedObjectContext:         [[DataManager sharedInstance] backgroundManagedObjectContext]];
  
                  [[DataManager sharedInstance] saveBackgroundContext];
                  [[DataManager sharedInstance] saveMasterContext];
  
                  NSLog(@" %@", cartVC.cart); 
              }
          }
  
      }
  
  
  
  }];
  </code></pre>
  
  <p>Save Context </p>
  
  <pre><code>-(void)saveCurrentContext:(NSManagedObjectContext *)context  {
  
      NSError *error = nil;
      if (![context save:&amp;error]) {
          NSLog(@"NOT SAVED");
      }
      [[DataManager sharedInstance] saveBackgroundContext];
      [[DataManager sharedInstance] saveMasterContext];
  
  
  
  }
  </code></pre>