从核心数据关系中删除对象 - NSSet

7c9*_*fdf 2 core-data objective-c ios

我在产品实体和购物车实体之间存在一对多关系。

用户需要有机会从购物车中删除产品。

我像这样获取产品:

         // 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;
Run Code Online (Sandbox Code Playgroud)

并填充表格视图:

Product *prod = (Product *)[self.fetchedResultsController objectAtIndexPath:indexPath];
Run Code Online (Sandbox Code Playgroud)

在tableview中我有一个按钮,当你点击它时,当前产品应该被删除......我的“删除产品方法”中有以下代码

-(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];




}
Run Code Online (Sandbox Code Playgroud)

但是什么也没有发生,当方法被触发时......产品不会从关系中删除。我该如何解决这个问题,我的代码在某处显然是错误的。

Mar*_*n R 5

要从购物车中删除产品,您可以使用

product.inCart = nil;
Run Code Online (Sandbox Code Playgroud)

或者

[_cart removeProductsObject:product];
Run Code Online (Sandbox Code Playgroud)

(如果逆关系设置正确,两条线是等效的。)