【问题标题】:Save many-to-one relationship from JSON into Core Data将 JSON 中的多对一关系保存到 Core Data
【发布时间】:2010-06-03 13:42:19
【问题描述】:

我想将从 JSON 解析的多对一关系保存到核心数据中。 解析 JSON 并插入 Core Data 的代码如下所示:

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”是 Core Data 生成的访问器方法。
成分和配方之间存在多对一的关系

  1. 但是,当我运行它时,我收到以下错误: NSCFDictionary managedObjectContext]: 无法识别的选择器发送到实例

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

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


更新 1:MOC 设置如下:
- (NSManagedObjectContext *)insertionContext {
if (insertionContext == nil) {
insertContext = [[NSManagedObjectContext alloc] init];
[insertionContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
}
返回插入上下文;
}

更新 2:
数据模型具有配方(对象类:配方)与成分(对象类:成分)的一对多关系。见:

如果,而不是:
[配方集成分:成分集]; 我尝试在 for 循环期间单独设置成分 - 例如使用:
recipe.ingredients = thisIngredient;
我收到错误消息:“警告:从不同的 Objective-C 类型传递 'setIngredients:' 的参数 1 时,不兼容的 Objective-C 类型'struct NSDictionary *',预期的'struct NSSet *'”

【问题讨论】:

  • 你有没有找到解决这个错误的方法:NSCFDictionary managedObjectContext]:

标签: iphone core-data


【解决方案1】:

您的问题是您如何获取未显示的托管对象上下文...它表示您正在调用字典上的 managedObjectContext 访问器或方法,因此出现错误,请发布您如何检索托管对象上下文,检查您调用该方法的对象,它似乎不是您要调用的对象...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多