我在产品实体和购物车实体之间存在一对多的关系。
用户需要有机会从购物车中删除产品。
我像这样获取产品:
// 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;
并填充tableview:
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];
}
但是当方法被触发时没有任何反应..产品不会从关系中删除。 我如何设法解决这个问题,我的代码在某处显然是错误的。
答案 0 :(得分:4)
要从购物车中移除产品,您可以使用
product.inCart = nil;
或
[_cart removeProductsObject:product];
(如果正确设置了反向关系,则两条线都是等效的。)
答案 1 :(得分:0)
[_theManagedObjectContext deleteObject:product];
这只适用于Xcode 7之后。 也许是因为实体+ CoreDataProperties类别创建引入的变化?