【问题标题】:Illegal attempt to establish a relationship 'object' between objects in different contexts非法尝试在不同上下文中的对象之间建立关系“对象”
【发布时间】:2016-07-12 20:23:06
【问题描述】:

我知道有几个问题可能重复出现,但是没有明确的解决方案可以解决我的问题,所以我决定发布我的具体案例。

我在我的应用程序中使用CoreData,并且一些对象被实例化而没有被有效地保存在地面上,我在这些情况下的启动代码如下:

-(id)initEntity:(NSManagedObjectContext*)context{
    AppDelegate appDelegate * = [[UIApplication sharedApplication] delegate];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Endereco" inManagedObjectContext: appDelegate.managedObjectContext];
    self = (Endereco*)[[Endereco alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];

    return self;
}

但是,这个对象的一个​​属性是已经保存在基础上的自治市,并由 ActionSheet 选择:

if (actionSheet == actionSheetMunicipios) {
        Municipio *municipio = [municipios objectAtIndex:buttonIndex-1];

        endereco.municipio = municipio;
        [textMunicipio setText:endereco.municipio.nome];
    }

排队

endereco.municipio = municipio;

我收到以下错误:

*** 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“非法尝试建立 不同上下文中对象之间的关系'municipio'。

错误很明显,我试图建立具有不同上下文的对象关系,但在我的情况下,父对象没有保存在基础上,并且子对象已经存在,我怎么能解决?

【问题讨论】:

    标签: ios core-data nsmanagedobject nsmanagedobjectcontext


    【解决方案1】:

    您的 cmets 似乎表明您知道答案。将endereco 添加到上下文中(使用insertIntoManagedObjectContext: context 而不是insertIntoManagedObjectContext: nil)。这不是得救的问题;您需要确保这两个对象位于相同的上下文中。没有办法解决这个问题。您无法在属性中创建跨上下文关系(您可以在获取的属性中创建,但这很复杂,而且这似乎不是您想要的情况)。

    【讨论】:

    • 朋友,感谢您的帮助,但我可以解决,否则请参阅我的答案。
    【解决方案2】:

    我设法通过在 Municipio 的 managedContext 中添加 Endereco 来解决问题:

       if (actionSheet == actionSheetMunicipios) {
            Municipio *municipio = [municipios objectAtIndex:buttonIndex-1];
            [municipio.managedObjectContext insertObject:endereco];
            [endereco setMunicipio:municipio];
            [textMunicipio setText:endereco.municipio.nome];
        }
    

    我不知道这是否是最好的解决方案,但在这种情况下效果很好。

    【讨论】:

      猜你喜欢
      • 2011-08-31
      • 2010-12-05
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多