简体   繁体   中英

Delete Object from Core data 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;

or

[_cart removeProductsObject:product];

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

[_theManagedObjectContext deleteObject:product];

这只适用于Xcode 7后的我。也许是因为实体+ CoreDataProperties类别创建引入的变化?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM