What’s new in Core Data Swift 3.0 – JaywayJayway

Core Data Basics: Preload Data and Use Existing SQLite Database

Core Data file’s Location iOS 10

“CoreData: error: Failed to load model named …” 

와 같은 에러가 발생하는 경우 

let container = NSPersistentContainer(name: “QuestionModel”)

에서 name 에 잘못된 이름을 넣어서 생긴것이 아니가 확인한다. 

그 이름은 .xcdatamodelid 화일명과 같아야 한다. 

오래전에 만들어진 tutorial이나 블로그 포스트를 보면 요즘(2018 6 10) 과 appdelegate에 있는 코드가 다른것을 알수 있다. 최근의 코드에서는 persistentContainer 를 통해 managedObjectContext, managedObjectModel, persistentStoreCoordinator 에 접근할수 있게 되었다.

최근)

// MARK: - Core Data stack

    lazy var persistentContainer: NSPersistentContainer = {
        /*
         The persistent container for the application. This implementation
         creates and returns a container, having loaded the store for the
         application to it. This property is optional since there are legitimate
         error conditions that could cause the creation of the store to fail.
        */
        let container = NSPersistentContainer(name: "test")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                 
                /*
                 Typical reasons for an error here include:
                 * The parent directory does not exist, cannot be created, or disallows writing.
                 * The persistent store is not accessible, due to permissions or data protection when the device is locked.
                 * The device is out of space.
                 * The store could not be migrated to the current model version.
                 Check the error message to determine what the actual problem was.
                 */
                fatalError("Unresolved error (error), (error.userInfo)")
            }
        })
        return container
    }()

    // MARK: - Core Data Saving support

    func saveContext () {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nserror = error as NSError
                fatalError("Unresolved error (nserror), (nserror.userInfo)")
            }
        }
        
        
    }



예전)

import CoreData
class CoreDataStack {
    // Applications default directory address
    lazy var applicationDocumentsDirectory: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
        // 1
        let modelURL = NSBundle.mainBundle().URLForResource("Supercars", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SuperCars.sqlite")
        do {
            // If your looking for any kind of migration then here is the time to pass it to the options
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch let  error as NSError {
           print("Ops there was an error (error.localizedDescription)")
           abort()
        }
        return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the
application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to
fail.
        let coordinator = self.persistentStoreCoordinator
        var context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
        context.persistentStoreCoordinator = coordinator
        return context
}()
// if there is any change in the context save it
func saveContext() {
        if mangagedObjectContext.hasChanges {
            do {
                try managedObjectContext.save()
            } catch let error as NSError {
                print("Ops there was an error (error.localizedDescription)")
                abort() 
      }
     } 
   }
}

Getting Started with Core Data Tutorial