我有這些實體:可可:如何避免核心數據重複的關係?
- ProductsEntity
- 名
- 訂單[ProductsOrderRelationship]
- OrderEntity
- 產品[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)
}
我找不到這個具體問題的指南..有什麼建議嗎?
避免重複的關係或複製數據的輸入? –