我需要在后台线程中执行时将数据保存到 CoreData。我发现了一些问题以及如何执行此操作的答案,但所有问题都与 objective-c 有关。也许有人会很友好地分享在 Swift 中在后台线程中保存数据的方法?
我使用的代码如下
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 _ {
}
}
}
提前致谢。
最佳答案
如果你打算在 swift 中编写代码,你最好也至少学会阅读 ObjC,因为绝大多数 iOS/OSX 代码都是用 ObjC 编写的。
此外,所有文档均以 ObjC 和 swift 格式提供,因此您应该能够在工作中使用它。
我根本不懂 swift,但我可以在没有编译器帮助的情况下在编辑器中完成这个基本转换(并且足够接近爵士乐)...
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.
}
关于swift - 如何使用 Swift 在后台线程中保存到 CoreData?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33423824/