如何使用Swift在后台线程中保存到CoreData?

时间:2015-10-29 20:19:28

标签: swift core-data

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


    }


}

提前致谢。

1 个答案:

答案 0 :(得分:13)

如果您要在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.
}