我需要在后台线程中执行数据时将数据保存到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 _ {
        }


    }


}

提前致谢。

最佳答案

如果您打算快速编写代码,那么最好也学会至少阅读ObjC,因为绝大多数iOS/OSX代码都是用ObjC编写的。

此外,所有文档都在ObjC和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将其保存到后台线程的Core Data中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33423824/

10-11 19:48
查看更多