我有这些实体:
- 产品实体
- 姓名
- 订单 [ProductsOrderRelationship]
- 订单实体
- 产品 [ProductsOrderRelationship]
- 产品订单关系
- 订单 [OrderEntity]
- 产品 [ProductsEntity]
- 数量
现在,我想编辑现有订单。我有一个可用产品列表和购物车。
现在我想将这些可用产品添加到购物车。
代码必须检查产品是否存在,所以它只会增加数量。
但是,到现在为止,它只是增加了更多的关系..
分享一段代码吧!该界面左侧有一个列表,其中包含可用产品,右侧有一个列表,其中包含购物车(订单实体)。两者都有链接到我的代码的数组控制器。然后我有这个动作:
- (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)
}
我找不到这个特定问题的指南。有什么建议吗?