我当前在应用程序中使用核心数据。我有以下实体:通知(to-1),人(to-to-many)。实体如下:
通知实体的模式
人物实体的模式
人民实体具有独特的约束,即字段ID。基本上,我将从人员那里收到通知(将保存在通知实体中)(将保存在人实体中)。如果具有特定ID的人发送多个通知并且不创建新的通知(这将是重复的),我想更新人员实体。
。当我进行上述时,我会收到以下错误:
操作无法完成。(可可错误133021。)
有人可以帮我解决这个问题。以下是我的代码,也是我要保存的数据的示例。
let entityNotification = NSEntityDescription.entityForName("Notification", inManagedObjectContext: self.managedContext)
let newNotification = Notification(entity: entityNotification!, insertIntoManagedObjectContext: self.managedContext)
newNotification.message = data["message"] as? String
if let actor = data["actor"] as? [String : AnyObject]
{
let newPeople = NSEntityDescription.insertNewObjectForEntityForName("People", inManagedObjectContext: self.managedContext) as! People
newPeople.id = actor["id"] as? Int
newPeople.name = actor["name"] as? String
newNotification.actor = newPeople
}
if let designator = data["designator"] as? [String : AnyObject]
{
let newPeople = NSEntityDescription.insertNewObjectForEntityForName("People", inManagedObjectContext: self.managedContext) as! People
newPeople.id = designator["id"] as? Int
newPeople.name = designator["name"] as? String
newNotification.designator = newPeople
}
do
{
try newNotification.managedObjectContext?.save()
}
catch let error as NSError
{
print(error.localizedDescription)
}
数据模型:
let notif = ["message" : "testing",
"actor" : ["id": 1, "name": "jim"],
"designator" : ["id": 2, "name": "dave"]]
let notif1 = ["message" : "testing 1",
"actor" : ["id": 1, "name": "jim21"],
"designator" : ["id": 2, "name": "dave"]]
解决您的重复创建问题的传统方法是对具有该身份的Person
进行提取请求,而不是创建新的。这可能是您的最佳选择,测试将说明
具有独特的约束,核心数据可以为您合并,但是您需要告诉它如何合并。目前,它通过丢弃错误来合并,这并不是那么有用。您需要将上下文中的mergePolicy
设置为NSMergeByPropertyObjectTrumpMergePolicy
,然后尝试一下,看看结果是否真的是您想要的...