核心数据一对多关系

时间:2012-08-07 17:44:40

标签: ios core-data

我有一个与一对多关系的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];
}

一切都是对的,但在[食谱addIngredientsObject:成分] ...

之后出了问题

发生了什么事?!无法摆脱这个问题!

2 个答案:

答案 0 :(得分:0)

修复了从一对多(Ingredients.foodItem)

中删除反向关系的问题

答案 1 :(得分:0)

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

请参阅核心数据编程指南中的示例Creating, Initializing, and Saving a Managed Object