CoreData 一对多关系
Posted
技术标签:
【中文标题】CoreData 一对多关系【英文标题】:CoreData one-to-many relationship 【发布时间】:2012-08-07 17:44:40 【问题描述】:我有一个具有一对多关系的 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 视为食谱,如果有 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] 之后出现问题...
这是怎么回事?!无法逃避这个问题!
【问题讨论】:
【参考方案1】:修复了从一对多(Ingredients.foodItem)中删除反向关系
【讨论】:
【参考方案2】:我不完全理解你在你的代码中试图做什么,但有一个基本问题:像Food
和Ingredient
这样的托管对象必须用initWithEntity:insertIntoManagedObjectContext:
正确初始化,你不能只是alloc+init他们。 (嗯,你可以,但它更复杂。)
请参阅 Core Data Programming Guide 中的例如 Creating, Initializing, and Saving a Managed Object。
【讨论】:
我有一个关于食品和配料的类别... - (id)init AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; NSManagedObjectContext *context = appDelegate.managedObjectContext; self = [super initWithEntity:[NSEntityDescription entityForName:@"Food" inManagedObjectContext:context] insertIntoManagedObjectContext:context];如果(自我)返回自我;以上是关于CoreData 一对多关系的主要内容,如果未能解决你的问题,请参考以下文章