gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:00:26 25 4
gpt4 key购买 nike

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

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

我这样获取产品:

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

并填充表格 View :

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

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




}

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

最佳答案

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

product.inCart = nil;

[_cart removeProductsObject:product];

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

关于ios - 从核心数据关系中删除对象 - NSSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17042421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com