2012-05-10 14 views
1

私は、これらのエンティティがあります。Cocoa:コアデータの重複関係を回避するにはどうすればよいですか?

  • 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) 
} 

私はこの特定の問題のガイドを見つけることができません..何か提案はありますか?

+0

は、重複関係を避けたり、データの入力を複製しますか? –

答えて

1

firstSelectedProductsにProductsEntityオブジェクトがあり、oldProductsにProductsOrderRelationshipオブジェクトが含まれていると思います。それが本当であれば、問題は...

if (![oldProducts containsObject:object]) { 

...決して決して一致しません。

(あなたがProductsOrderRelationshipがしばしばあるLineItemと呼ばれる呼び出すどのようなクラスの名前を変更すると、それに関連する変数はロジックをより明確にすることがあります。)

+0

ありがとう!私はより良い点検をした。 – Apollo

関連する問題