2

我在 Product 实体和 Cart 实体之间有一对多的关系。

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

我像这样获取产品:

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

并填充表格视图:

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

在表格视图中,我有一个按钮,当您点击它时,应该删除当前产品...我的“删除产品方法”中有以下代码

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




}

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

4

2 回答 2

5

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

product.inCart = nil;

或者

[_cart removeProductsObject:product];

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

于 2013-06-11T11:21:19.467 回答
0
[_theManagedObjectContext deleteObject:product];

这仅在 Xcode 7 之后对我有用。也许是因为引入了关于实体+CoreDataProperties 类别创建的更改?

于 2015-11-24T16:03:28.243 回答