【问题标题】:The operation couldn’t be completed. (Cocoa error 133021.) + swift 2操作无法完成。 (可可错误 133021。)+ swift 2
【发布时间】:2016-06-16 05:47:28
【问题描述】:

我目前在我的应用程序中使用核心数据。我有以下实体:通知(to-1),人员(to-many)。实体如下:

schema for Notification entity

schema for People entity

People 实体有一个唯一的约束,即字段 id。基本上,我将接收来自人员(将保存在人员实体中)的通知(将保存在通知实体中)。如果具有特定 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)
    }

数据模型:

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"]]

【问题讨论】:

  • 您的代码中没有任何地方尝试加载现有的 g People 实例

标签: ios swift cocoa core-data


【解决方案1】:

解决重复创建问题的传统方法是使用该身份对Person 执行获取请求并更新,而不是创建新的。这也可能是您的最佳选择,测试会告诉您。

具有独特约束的核心数据可以为您进行合并,但您需要告诉它如何进行。目前它通过抛出错误进行合并,这不是那么有用。您需要将上下文中的mergePolicy 设置为NSMergeByPropertyObjectTrumpMergePolicy,然后尝试一下,看看结果是否真的是您想要的...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2013-03-27
    • 2017-07-28
    相关资源
    最近更新 更多