2017-02-26 50 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

偉大的例子名稱在一個很好的答案。 –