核心数据:将关系对象添加到现有对象

时间:2016-01-13 05:26:25

标签: ios objective-c core-data

我的核心数据中有以下实体

  • 消息

其中关系如下。

  • 消息hasDepartment(to one)
  • 部门hasMessage(对很多人)

部门已插入核心数据中。当新消息到达时,我将其插入核心数据并添加部门关系,但应用程序崩溃并出现以下错误。

  

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

以下是我设置消息对象的代码段

reentrant

注意:所有操作都是使用核心数据中的NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context]; // find department object from core data. Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]]; // Create new message object Message *objMessage = [[Message alloc] initWithEntity:entity insertIntoManagedObjectContext:context]; // *** Establish relation with department *** if(objDepartment != nil) { // app crashes here... [objMessage setDepartment:objDepartment]; } [objMessage setLastUpdatedTime:[NSDate date]]; } // *** Set other values in message object *** 上下文完成的。

任何建议或帮助都将不胜感激。

2 个答案:

答案 0 :(得分:1)

看起来部门是从不同的上下文中获取的,您需要从相同的上下文中获取部门对象。试试这是否有效:

Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]];

// Get department in in current context 
NSError *error = nil;
objDepartment = [context objectWithID:objDepartment.objectId error:&error]

答案 1 :(得分:0)

您需要使用NSFetchRequest

获取特定记录以进行更新
// find department object from core data.
Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Message"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"Message==%@",txtMessage]; // If required to fetch specific vehicle
fetchRequest.predicate=predicate;
Message *objMessage = [[context executeFetchRequest:fetchRequest error:nil] lastObject];
if(objDepartment != nil)
{
   // app crashes here...
   [objMessage setDepartment:objDepartment];
}
[objMessage setLastUpdatedTime:[NSDate date]];
NSError *error;
if (![context save:&error]) {
     NSLog(@"Whoops, couldn't Update: %@", [error localizedDescription]);
  }
  else{
        //updated successfully
}

//用于插入新记录

Message *objMessage = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];

希望它可以帮助你......!