I’ve got a Food entity with a one-to-many relationship:
- (void)addIngredientsObject:(Ingredient *)value;
- (void)removeIngredientsObject:(Ingredient *)value;
- (void)addIngredients:(NSSet *)values;
- (void)removeIngredients:(NSSet *)values;
The Ingredient entity has:
@class Food;
@interface Ingredient : NSManagedObject
@property (nonatomic, strong) NSNumber * quantity;
@property (nonatomic, strong) NSString * recordUUID;
@property (nonatomic, strong) Food *foodItem;
@end
I consider a Food like a recipe, if there are items for Food.ingredients, it’s a recipe, otherwise not.
Now when I try to add Ingredients to my (Food) recipe:
Ingredient *recipeIngredient = [[Ingredient alloc] init];
recipeIngredient.foodItem = ingredient;
NSLog(@"ingredient: %@", ingredient.name);
recipeIngredient.quantity = q;
[addRecipeController.items addObject:recipeIngredient];
and
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]);
it saves successfully.
But when I go into the details and try to check it out the ingredients of my recipe…
NSMutableSet *foods = [item mutableSetValueForKey:@"ingredients"];
for(Ingredient *ing in foods) {
NSLog(@"Class: %@", NSStringFromClass([ing.foodItem class]));
NSLog(@"Name: %@", ing.foodItem.name);
}
I’ve got that all the ingredient’s name are equal to the recipe ingredient… and that’s wrong… If I try to log the names in this loop:
// Compute
for(Ingredient *ingredient in items) {
// NSLOG for food name here
[recipe addValuesFromFood:ingredient.foodItem withQuantity:ingredient.quantity];
[recipe addIngredientsObject:ingredient];
}
everything is right, but things go wrong after [recipe addIngredientsObject:ingredient]…
What’s going on?! Cannot escape from this issue!
fixed removing the inverse relationship from the one-to-many (Ingredients.foodItem)