【问题标题】:inputing many objects into core data in one go一次性将多个对象输入核心数据
【发布时间】:2017-02-26 12:25:56
【问题描述】:

我有很多对象想一次性放入核心数据属性中,有没有一种快速的方法?我知道你使用这个系统来创建对象,但你必须一次又一次地运行它来添加新对象。

       let appDelegate = UIApplication.shared.delegate as! AppDelegate

    let context = appDelegate.persistentContainer.viewContext

   let newName = NSEntityDescription.insertNewObject(forEntityName: "StoredNames", into: context)

    newName.setValue("Jim", forKey: "name")

有没有快速的解决方案?一种我可以一次性将许多名称添加到名称属性中的方法。

【问题讨论】:

    标签: database object core-data swift3 attributes


    【解决方案1】:

    如果您想使用NSPersistentContainer,您应该将viewContext 视为只读。如果你想插入核心数据,你应该使用performBackgroundTask,它为你提供了一个插入的上下文。在该块中插入所有内容并在最后调用 save 一次。这将避免多次保存核心数据。

     let lotsOfStuffToInsert = ["Eugenio Barefoot",
            "Shaquita Lettieri",
            "Tami Hollingworth",
            "Marion Pruitt",
            "Hubert Pigeon",
            "Stewart Christon",
            "Clarence Murry",
            "Roni Bohnsack",
            "Mozell Oberman",
            "Mellissa Dowd",
            "Sybil Swinton"]
    self.persistentContainer.performBackgroundTask { (managedObjectContext) in
        for name in lotsOfStuffToInsert{
            let newName = NSEntityDescription.insertNewObject(forEntityName: "StoredNames", into: managedObjectContext)
            newName.setValue(name, forKey: "name")
        }
        do {
            try managedObjectContext.save()
        } catch {
    
        }
    }
    

    还要确保添加核心数据设置

    container.viewContext.automaticallyMergesChangesFromParent = true
    

    【讨论】:

    • 对不起,我不太明白你的意思,你能用一些代码演示一下吗?我以前从未遇到过 performBackgrounTask
    • 一个很好的答案中的很好的例子名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-01
    相关资源
    最近更新 更多