Remove the object from the database relationship – NSSet

I have a one to many relationship between a Product entity and a Cart Entity.

The user needs to have the opportunity to delete a product from the cart.

I fetch the products like so:

// 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;

and populate the tableview:

Product *prod = (Product *)[self.fetchedResultsController objectAtIndexPath:indexPath];

In the tableview I have a button and when you tap it, that current product, should get deleted… I have the following code in my “delete product method”

-(void)RemoveFromCart:(UIButton *)sender {

    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    NSIndexPath *indexPath = [_Table indexPathForCell:cell];

    Product *prod = (Product *)[self.fetchedResultsController objectAtIndexPath:indexPath];

    /*_cart is retrieved when the user pushes the add to cart button, in another    viewcontroller, a cart object is then returned and passed to the cart viewcontroller */
    NSMutableSet *mutableSet = [NSMutableSet setWithSet:_cart.products];

        [mutableSet removeObject:prod];
        _cart.products = mutableSet;

    [self saveCurrentContext:_theManagedObjectContext];

    [_Table reloadData];


But nothing happens, when the method is fired.. the product is not removed from the relationship. How do I manage to fix this, my code is obviously wrong somewhere.

To remove a product from the cart, you can either use

product.inCart = nil;


[_cart removeProductsObject:product];

(Both lines are equivalent if the inverse relationships are properly set up.)

Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 移动开发 » Remove the object from the database relationship – NSSet

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录