2017-02-26 62 views
0

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

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

有没有快速解决这个问题?我可以一次性将许多名称添加到name属性中。

回答

1

如果您要使用NSPersistentContainer,则应该将viewContext视为只读。如果你想插入核心数据,你应该使用performBackgroundTask,它给你一个上下文来插入。做所有插入该块并在最后呼叫保存一次。这将避免多次保存到核心数据。

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 
+0

对不起,我不太明白你的意思,你可以用一些代码来证明?我从来没有遇到过performBackgrounTask之前 –

+0

伟大的例子名称在一个很好的答案。 –