iMo*_*and 4 cocoa core-data ios swift
我目前正在我的应用程序中使用核心数据.我有以下实体:通知(to-1),People(to-many).实体如下:
People实体具有唯一约束,即字段id.基本上我将从人员(将保存在People实体中)接收通知(将保存在通知实体中).如果具有特定ID的人发送多个通知而不创建新通知(这将是重复的),我想更新People实体.
当我做上述操作时,我收到以下错误:
该操作无法完成.(可可错误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)
}
Run Code Online (Sandbox Code Playgroud)
数据模型:
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"]]
Run Code Online (Sandbox Code Playgroud)
解决重复创建问题的传统方法是Person使用该标识进行获取请求并更新,而不是创建新的.测试将告诉你,这也许是你的最佳选择.
凭借独特的约束,核心数据可以为您进行合并,但您需要告诉它如何.目前它正在通过抛出错误来合并,这不是很有用.你需要mergePolicy在上下文中设置NSMergeByPropertyObjectTrumpMergePolicy,然后尝试一下,看看结果是否真的是你想要的......