如何使用Swift在后台线程中保存CoreData?
当CoreData在后台线程中执行时,我需要将数据保存到CoreData。我发现了一些问题和答案如何做到这一点,但它们都与objective-c有关。也许有人会很乐意在Swift中共享在后台线程中保存数据的方法 我使用的代码如下如何使用Swift在后台线程中保存CoreData?,swift,core-data,Swift,Core Data,当CoreData在后台线程中执行时,我需要将数据保存到CoreData。我发现了一些问题和答案如何做到这一点,但它们都与objective-c有关。也许有人会很乐意在Swift中共享在后台线程中保存数据的方法 我使用的代码如下 override func viewDidLoad() { dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
override func viewDidLoad() {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
[unowned self] in
saveArticlesListToDb("Specs")
}
}
func saveArticlesListToDb(category:String) {
var counter:Int = 0
var array:[ArticlesList] = []
if category == "Battles" {
array = self.battlesArticlesListArrayToSave
} else if category == "Specs" {
array = self.specsArticlesListArrayToSave
} else if category == "Guide" {
array = self.guideArticlesListArrayToSave
}
let appDelegate : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext : NSManagedObjectContext = appDelegate.managedObjectContext
let entity = NSEntityDescription.entityForName("ArticlesListDB", inManagedObjectContext: managedContext)
for var i = 0; i < array.count; ++i {
let articlesList = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
articlesList.setValue(array[i].id, forKey: "id")
articlesList.setValue(array[i].title, forKey: "title")
articlesList.setValue(array[i].subtitle, forKey: "subtitle")
articlesList.setValue(array[i].image, forKey: "image")
articlesList.setValue("\(category)", forKey: "categoryName")
counter++
do {
try managedContext.save()
} catch _ {
}
}
}
重写func viewDidLoad(){
调度异步(调度获取全局队列(QOS类用户发起,0)){
[无主的自己]在
saveArticlesListToDb(“规范”)
}
}
func saveArticlesListToDb(类别:字符串){
变量计数器:Int=0
变量数组:[ArticlesList]=[]
如果类别==“战斗”{
array=self.battlesArticleListArrayToSave
}否则,如果类别=“规格”{
array=self.specsArticlesListArrayToSave
}如果类别==“指南”,则为else{
数组=self.guideArticleSlistarayToSave
}
让appDelegate:appDelegate=UIApplication.sharedApplication().delegate为!appDelegate
让managedContext:NSManagedObjectContext=appDelegate.managedObjectContext
让entity=NSEntityDescription.entityForName(“ArticlesListDB”,在ManagedObjectContext:managedContext中)
对于变量i=0;i
提前感谢。如果您打算用swift编写代码,您最好至少也学会阅读ObjC,因为绝大多数iOS/OSX代码都是用ObjC编写的 此外,所有文档都是ObjC和swift格式的,因此您应该能够在工作中使用它们 我一点也不知道swift,但我可能可以在编辑器中完成这个基本转换,而无需编译器帮助(并且可以接近jazz)
你真的救了我。非常感谢!当performblock的代码完成时,我需要completionHandler
let privateContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator = managedContext.persistentStoreCoordinator
privateContext.performBlock {
// Code in here is now running "in the background" and can safely
// do anything in privateContext.
// This is where you will create your entities and save them.
}