 import UIKit
 import CoreData
 
+let CoreDataWriteQueue: dispatch_queue_t = dispatch_queue_create("BraveDataWriteQueue", DISPATCH_QUEUE_SERIAL)
+
 class DataController: NSObject {
     static let singleton = DataController()
     
     private var _managedObjectContext: NSManagedObjectContext? = nil
     var managedObjectContext: NSManagedObjectContext? {
         get {
-            if NSThread.isMainThread() == true {
+            if NSThread.isMainThread() {
                 return mainThreadContext()
-            } else {
+            }
+            else {
                 return writeContext()
             }
         }

    private var managedObjectModel: NSManagedObjectModel!
    private var persistentStoreCoordinator: NSPersistentStoreCoordinator!
    
    let CoreDataWriteQueue: dispatch_queue_t = dispatch_queue_create("BraveDataWriteQueue", DISPATCH_QUEUE_SERIAL)
    
    override init() {
        super.init()
        
        guard let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension:"momd") else {

        if managedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            }
            catch {
                fatalError("Error migrating store: \(error)")
            }
        }
    }
    
    // DataController.write {...} closure execute data updates before context save.
    static func write(closure: ()->void) {
        dispatch_async(CoreDataWriteQueue) {
            closure()
            DataController.saveContext()
        }
    }
    
