0

1 対多の関係を持つ Food エンティティがあります。

- (void)addIngredientsObject:(Ingredient *)value;
- (void)removeIngredientsObject:(Ingredient *)value;
- (void)addIngredients:(NSSet *)values;
- (void)removeIngredients:(NSSet *)values;

Ingredient エンティティには次のものがあります。

@class Food;

@interface Ingredient : NSManagedObject

@property (nonatomic, strong) NSNumber * quantity;
@property (nonatomic, strong) NSString * recordUUID;
@property (nonatomic, strong) Food *foodItem;

@end

私は Food をレシピのようなものと考えています。Food.ingredients の項目があればそれはレシピですが、そうでない場合はそうではありません。

(食品)レシピに材料を追加しようとすると:

    Ingredient *recipeIngredient = [[Ingredient alloc] init];
recipeIngredient.foodItem = ingredient;
NSLog(@"ingredient: %@", ingredient.name);
recipeIngredient.quantity = q;

[addRecipeController.items addObject:recipeIngredient];

    recipe = [[Food alloc] init];

// Controllare che il nome sia univoco
recipe.name = nameTextField.text;

// Compute
for(Ingredient *ingredient in items) {
    [recipe addValuesFromFood:ingredient.foodItem withQuantity:ingredient.quantity];
    [recipe addIngredientsObject:ingredient];
}

// Defaults
recipe.bookmark = [NSNumber numberWithBool:NO];
recipe.complex = [NSNumber numberWithBool:YES];
recipe.dirty = [NSNumber numberWithBool:NO];
recipe.lookback = [NSNumber numberWithBool:YES];
recipe.userAdd = [NSNumber numberWithBool:YES];

NSLog(@"pro: %f", recipe.pro.floatValue);
NSLog(@"items: %d", [recipe.ingredients count]);

正常に保存されます。

でも詳しく調べてみるとレシピの材料が…。

    NSMutableSet *foods = [item mutableSetValueForKey:@"ingredients"];
for(Ingredient *ing in foods) {
    NSLog(@"Class: %@", NSStringFromClass([ing.foodItem class]));
    NSLog(@"Name: %@", ing.foodItem.name);
}

すべての材料の名前がレシピの材料と同じであることがわかりました...そしてそれは間違っています...このループで名前をログに記録しようとすると:

    // Compute
for(Ingredient *ingredient in items) {
    // NSLOG for food name here
    [recipe addValuesFromFood:ingredient.foodItem withQuantity:ingredient.quantity];
    [recipe addIngredientsObject:ingredient];
}

すべてが正しいのですが、[recipe addIngredientsObject:ingredient] の後で問題が発生します...

どうしたの?!この問題から逃れることはできません!

4

2 に答える 2

0

1 対多 (Ingredients.foodItem) からの逆関係の削除を修正しました。

于 2012-08-07T18:22:05.877 に答える
0

コードで何をしようとしているのか完全には理解できませんが、基本的な問題が 1 つあります。 のような管理対象オブジェクトFoodIngredientで適切に初期化する必要がありますinitWithEntity:insertIntoManagedObjectContext:。単に alloc+init することはできません。(まあ、できますが、もっと複雑です。)

たとえば、Core Data Programming Guideの「 Creating, Initializing, and Saving a Managed Object」を参照してください。

于 2012-08-07T18:23:50.193 に答える