我有这些实体:
现在,我想编辑现有订单。我有一个可用的产品清单和购物车。
现在我想将这些可用的产品添加到购物车中。
代码必须检查产品是否存在,因此只会增加数量。
但是,到目前为止,它只是增加了更多的关系......
让我分享一段代码! 界面左侧列有可用产品,右侧列表带有购物车(订单实体)。两者都有链接到我的代码的数组控制器。然后我有这个动作:
- (IBAction)addSelectedProducts:(id)sender {
NSArray *firstSelectedProducts = [availableProductsController selectedObjects];
//Objects selected in the array controller
NSMutableArray *selectedProducts = [[NSMutableArray alloc] initWithCapacity:1];
//Here I will filter the repeated ones
NSMutableSet *newProducts = [NSMutableSet set];
//This is the final value to change in the current order entry.
NSMutableSet *oldProducts = [orderManagedObject valueForKey:@"products"];
//This is the old value I will change.
//Here we filter every repeated entries:
if ( [firstSelectedProducts count] > 0 ) {
for (id object in firstSelectedProducts) {
if (![oldProducts containsObject:object]) {
[selectedProducts addObject:object];
}
}
}
//Here we create objects in the relationship entity:
for (int i = 0; i < [selectedProducts count]; i++) {
// Create new relationship.
NSManagedObject *newProductObject = [
NSEntityDescription
insertNewObjectForEntityForName:@"ProductsOrderRelationship"
inManagedObjectContext:managedObjectContext
];
[newProductObject setValue:[selectedProducts objectAtIndex:i] forKey:@"product"];
[newProductObject setValue:orderManagedObject forKey:@"order"];
[newProducts addObject:newProductObject];
[newProductObject release];
}
[newProducts unionSet:oldProducts];
//Join old products and new products.
[orderManagedObject setValue:newProducts forKey:@"products"];
//Re-set the value.
//(... release stuff here)
}
我找不到这个具体问题的指南..有什么建议吗?
答案 0 :(得分:1)
我猜测firstSelectedProducts
包含ProductsEntity对象,oldProducts
包含ProductsOrderRelationship对象。如果这是真的,问题是......
if (![oldProducts containsObject:object]) {
......永远不会匹配任何东西。
(你所谓的ProductsOrderRelationship通常被称为LineItem。更改类的名称及其相关变量可能会使逻辑更清晰。)