0

我有一个具有一对多关系的 Food 实体:

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

成分实体具有:

@class Food;

@interface Ingredient : NSManagedObject

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

@end

我认为食物就像一个食谱,如果有 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

修复了从一对多(Ingredients.foodItem)中删除反向关系

于 2012-08-07T18:22:05.877 回答
0

我不完全理解您在代码中尝试做什么,但有一个基本问题:托管对象喜欢Food并且Ingredient必须正确初始化initWithEntity:insertIntoManagedObjectContext:,您不能只分配 + 初始化它们。(嗯,你可以,但它更复杂。)

例如,参见Core Data Programming Guide中的创建、初始化和保存托管对象

于 2012-08-07T18:23:50.193 回答