Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CoreData stack for iOS 9 and iOS 10 using Swift 3
//
// Storage.swift
//
// Created by Grigory Avdyushin on 30.06.16.
// Copyright © 2016 Grigory Avdyushin. All rights reserved.
//
import UIKit
import CoreData
/// NSPersistentStoreCoordinator extension
extension NSPersistentStoreCoordinator {
/// NSPersistentStoreCoordinator error types
public enum CoordinatorError: Error {
/// .momd file not found
case modelFileNotFound
/// NSManagedObjectModel creation fail
case modelCreationError
/// Gettings document directory fail
case storePathNotFound
}
/// Return NSPersistentStoreCoordinator object
static func coordinator(name: String) throws -> NSPersistentStoreCoordinator? {
guard let modelURL = Bundle.main.url(forResource: name, withExtension: "momd") else {
throw CoordinatorError.modelFileNotFound
}
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
throw CoordinatorError.modelCreationError
}
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
guard let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
throw CoordinatorError.storePathNotFound
}
do {
let url = documents.appendingPathComponent("\(name).sqlite")
let options = [ NSMigratePersistentStoresAutomaticallyOption : true,
NSInferMappingModelAutomaticallyOption : true ]
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)
} catch {
throw error
}
return coordinator
}
}
struct Storage {
static var shared = Storage()
@available(iOS 10.0, *)
private lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Model")
container.loadPersistentStores { (storeDescription, error) in
print("CoreData: Inited \(storeDescription)")
guard error == nil else {
print("CoreData: Unresolved error \(error)")
return
}
}
return container
}()
private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
do {
return try NSPersistentStoreCoordinator.coordinator(name: "Model")
} catch {
print("CoreData: Unresolved error \(error)")
}
return nil
}()
private lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: Public methods
enum SaveStatus {
case saved, rolledBack, hasNoChanges
}
var context: NSManagedObjectContext {
mutating get {
if #available(iOS 10.0, *) {
return persistentContainer.viewContext
} else {
return managedObjectContext
}
}
}
mutating func save() -> SaveStatus {
if context.hasChanges {
do {
try context.save()
return .saved
} catch {
context.rollback()
return .rolledBack
}
}
return .hasNoChanges
}
}
@ArsalanGhaffar

This comment has been minimized.

Copy link

ArsalanGhaffar commented Dec 15, 2016

hi, how to access app group container with core data stack for ios 10... with
static let applicationGroupIdentifier = "com.fetchDatainExtension"
if let newURL =
FileManager.default.containerURL(
forSecurityApplicationGroupIdentifier: "group.com.fetchDatainExtension.contacts") {
url = newURL
}

@pdecarcer

This comment has been minimized.

Copy link

pdecarcer commented Feb 14, 2017

Hi, I am new on swift 3 and I need to implement this file. How I can init this file

@TheEngineerz

This comment has been minimized.

Copy link

TheEngineerz commented Apr 6, 2017

Great

@InstaRobot

This comment has been minimized.

Copy link

InstaRobot commented Jan 16, 2018

Excellent. Thanks!

@nguyenthelinh296

This comment has been minimized.

Copy link

nguyenthelinh296 commented May 19, 2018

Good job sir, thank you very much

@johncristobal

This comment has been minimized.

Copy link

johncristobal commented Sep 24, 2018

Thanks! Great job.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.