Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How save to CoreData in background thread using Swift?

I need to save data to CoreData while it performs in background thread. I have found some questions with answers how to do this, but all of them are related to objective-c. Maybe some one would be so kind to share the method of saving data in background thread in Swift ?

The code that i use is following

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 _ {
        }


    }


}

Thanks in advance.

like image 964
Alexey K Avatar asked Oct 29 '15 20:10

Alexey K


1 Answers

If you are going to write code in swift, you better also learn to at least read ObjC as the vast majority of iOS/OSX code is written in ObjC.

Furthermore, all of the documentation is in both ObjC and swift, so you should be able to use that in your efforts.

I don't know swift at all, but I can probably do this basic conversion in the editor with no compiler help (and get close enough for jazz)...

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.
}
like image 64
Jody Hagins Avatar answered Dec 28 '22 03:12

Jody Hagins