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] の後で問題が発生します...
どうしたの?!この問題から逃れることはできません!