2010-06-03 45 views
0

我想将从JSON解析出的多对一关系保存到核心数据中。 该解析JSON并执行插入到核心数据的代码看起来是这样的:将JSON中的多对一关系保存到核心数据中

for (NSDictionary *thisRecipe in recipes) { 
    Recipe *recipe = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:insertionContext]; 
    recipe.name = [thisRecipe objectForKey:@"Title"]; 
    NSDictionary *ingredientsForRecipe = [thisRecipe objectForKey:@"Ingredients"]; 
    NSArray *ingredientsArray = [ingredientsForRecipe objectForKey:@"Results"]; 
    for (NSDictionary *thisIngredient in ingredientsArray) { 
    Ingredient *ingredient = [NSEntityDescription insertNewObjectForEntityForName:@"Ingredient" inManagedObjectContext:insertionContext]; 
    ingredient.name = [thisIngredient objectForKey:@"Name"]; 
    } 
} 
NSSet *ingredientsSet = [NSSet ingredientsArray]; 
[recipe setIngredients:ingredientsSet]; 

注: “setIngredients”是一个核心数据生成的访问方法。
有成分和配方之间的多到一的关系

  1. 然而,当我运行此我得到以下错误: NSCFDictionary managedObjectContext]:无法识别的选择发送到实例

  2. 如果我删除了最后一行(即[recipe setIngredients:ingredientsSet];) 然后,通过查看SQLite数据库,我看到配方和配料已经存储,但配方和配料之间没有建立任何关系

有关如何确保关系正确存储的任何建议?


更新1:MOC设置是这样的:
- (的NSManagedObjectContext *)insertionContext {
如果(insertionContext ==无){
insertionContext = [[ALLOC的NSManagedObjectContext] INIT];
[insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
return insertionContext;
}

更新2:
数据模型具有用于配方对多关系(对象类别:配方)用于成分(对象类别:成分)。参见:

http://i50.tinypic.com/10x98p4.jpg

如果,代替:
[配方setIngredients:ingredientsSet]; 我尝试在for循环中单独设置成分 - 例如使用:
recipe.ingredients = thisIngredient;
我得到错误信息: “警告:不兼容的Objective-C型 '结构的NSDictionary *',预期 '结构的NSSet *' 传递的参数1时:从不同的Objective-C型 'setIngredients'”

+0

你有没有找到这个错误的解决方案:NSCFDictionary managedObjectContext]: – 2012-01-03 22:06:54

回答

0

您的问题这里是你如何获得你没有显示的托管对象上下文......它表示你正在调用托管对象上的托管对象或方法,因此错误,发布你如何检索托管对象上下文,检查对象你调用该方法,它似乎不是你想要调用的对象...