<commit_before>//
//  PersistenceController.swift
//  TaskScheduler
//
//  Created by <NAME> on 12/29/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import Foundation
import CoreData
import JSQCoreDataKit

protocol PersistenceControllerDelegate: class {
    func persitenceControllerDataChanged()
}

class PersistenceController: NSObject {

    static let sharedInstance = PersistenceController()
    
    private var delegates: [PersistenceControllerDelegate]
    private var latestUser: User?
    var coreDataStack: CoreDataStack?
    
    private lazy var fetchedResultsController: NSFetchedResultsController = {
        let model = CoreDataModel(name: "TaskScheduler", bundle: NSBundle(identifier: "com.boztalay.TaskScheduler")!)
        self.coreDataStack = CoreDataStack(model: model)
        
        let fetchRequest = NSFetchRequest(entityName: "User")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sunAvailableWorkTime", ascending: true)]
        fetchRequest.includesSubentities = true
        
        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataStack!.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
        
        self.subscribeToDataSaves()
        
        return controller
    }()
    
    func handleManagedObjectContextDidSave(notification: NSNotification) {
        updateLatestUser()
        
        for delegate in self.delegates {
            delegate.persitenceControllerDataChanged()
        }
    }
    
    private func subscribeToDataSaves() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleManagedObjectContextDidSave:"), name: NSManagedObjectContextDidSaveNotification, object: self.coreDataStack!.managedObjectContext)
    }
    
    override init() {
        self.delegates = []

        super.init()

        updateLatestUser()
    }
    
    private func updateLatestUser() {
        try! fetchedResultsController.performFetch()
        if let fetchedObjects = self.fetchedResultsController.fetchedObjects {
            if fetchedObjects.count > 0 {
                self.latestUser = fetchedObjects[0] as? User
                return
            }
        }<commit_msg>PersistenceControllerDelegates now receive data changed notifications on the main thread to avoid nasty UI-updated-from-not-main-thread issues<commit_after>//
//  PersistenceController.swift
//  TaskScheduler
//
//  Created by <NAME> on 12/29/15.
//  Copyright © 2015 <NAME>. All rights reserved.
//

import Foundation
import CoreData
import JSQCoreDataKit

protocol PersistenceControllerDelegate: class {
    func persitenceControllerDataChanged()
}

class PersistenceController: NSObject {

    static let sharedInstance = PersistenceController()
    
    private var delegates: [PersistenceControllerDelegate]
    private var latestUser: User?
    var coreDataStack: CoreDataStack?
    
    private lazy var fetchedResultsController: NSFetchedResultsController = {
        let model = CoreDataModel(name: "TaskScheduler", bundle: NSBundle(identifier: "com.boztalay.TaskScheduler")!)
        self.coreDataStack = CoreDataStack(model: model)
        
        let fetchRequest = NSFetchRequest(entityName: "User")
        fetchRequest.sortDescriptors = [NSSortDescriptor(key: "sunAvailableWorkTime", ascending: true)]
        fetchRequest.includesSubentities = true
        
        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.coreDataStack!.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)
        
        self.subscribeToDataSaves()
        
        return controller
    }()
    
    func handleManagedObjectContextDidSave(notification: NSNotification) {
        updateLatestUser()
        
        for delegate in self.delegates {
            dispatch_async(dispatch_get_main_queue()) {
                // Calling this in the main queue to avoid updating the UI on
                // a different thread, might need to change in the future so that
                // delegates handle this themselves in a more precise fashion. But
                // for now, I haven't noticed any performance issues.
                delegate.persitenceControllerDataChanged()
            }
        }
    }
    
    private func subscribeToDataSaves() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleManagedObjectContextDidSave:"), name: NSManagedObjectContextDidSaveNotification, object: self.coreDataStack!.managedObjectContext)
    }
    
    override init() {
        self.delegates = []

        super.init()

        updateLatestUser()
    }
    
    private func updateLatestUser() {
        try! fetchedResultsController.performFetch()
        if let fetchedObjects = self.fetchedResultsController.fetchedObjects {
            if fetchedObjects.count > 0 {
                self.latestUser = fetchedObjects[0] as? User
                return
            }
        }
{'fraction_non_alphanumeric': 0.07560684440907282, 'fraction_numerical': 0.00477516912057302, 'mean_word_length': 2.9304143862392493, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4542114', 'n_tokens_mistral': 1304, 'n_tokens_neox': 1254, 'n_words': 305}