[Tutoriel] Séparation de CoreData de l'AppDelegate

Joanna CarterJoanna Carter Membre, Modérateur

Je propose de séparer le "stack" CoreData de l'AppDelegate, parce que ça simplifie le code dans l'AppDelegate et rend le stack disponible de n'importe où dans les autres classes.


 


J'ai supprimé tous les commentaires pour la clarté



class DataProvider
{
private init() { }

static let shared = DataProvider()

private lazy var persistentContainer: NSPersistentContainer =
{
let container = NSPersistentContainer(name: "Draken")

container.loadPersistentStores(completionHandler:
{
(storeDescription, error) in

if let error = error
{
fatalError("Unresolved error \(error)")
}
})

return container
}()

var undoManager: UndoManager?
{
return persistentContainer.viewContext.undoManager
}

var viewContext: NSManagedObjectContext
{
return persistentContainer.viewContext
}

func save()
{
let context = persistentContainer.viewContext

if !context.commitEditing()
{
NSLog("\(self) unable to commit editing before saving")
}

if context.hasChanges
{
do
{
try context.save()
}
catch
{
let nserror = error as NSError

NSApplication.shared().presentError(nserror)
}
}
}
}


@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
func windowWillReturnUndoManager(window: NSWindow) -> UndoManager?
{
return DataProvider.shared.undoManager
}

func applicationShouldTerminate(_ sender: NSApplication) -> NSApplicationTerminateReply
{
let context = DataProvider.shared.viewContext

if !context.commitEditing()
{
NSLog("\(NSStringFromClass(type(of: self))) unable to commit editing to terminate")

return .terminateCancel
}

if !context.hasChanges
{
return .terminateNow
}

do
{
try context.save()
}
catch
{
let nserror = error as NSError

let result = sender.presentError(nserror)

if (result)
{
return .terminateCancel
}

let question = NSLocalizedString("Could not save changes while quitting. Quit anyway?", comment: "Quit without saves error question message")

let info = NSLocalizedString("Quitting now will lose any changes you have made since the last successful save", comment: "Quit without saves error question info")

let quitButton = NSLocalizedString("Quit anyway", comment: "Quit anyway button title")

let cancelButton = NSLocalizedString("Cancel", comment: "Cancel button title")

let alert = NSAlert()

alert.messageText = question

alert.informativeText = info

alert.addButton(withTitle: quitButton)

alert.addButton(withTitle: cancelButton)

let answer = alert.runModal()

if answer == NSAlertSecondButtonReturn
{
return .terminateCancel
}
}

return .terminateNow
}
}

Connectez-vous ou Inscrivez-vous pour répondre.