How to initialise Core Data managedObjectContext using a model class?
How to initialise Core Data managedObjectContext using a model class?
I am following Apple Documentation for core data stack, especially Initializing the Core Data Stack.
Here is my code:
import Foundation
import CoreData
class Cmodel: NSObject {
var managedObjectContext: NSManagedObjectContext
init(completionClosure: @escaping () -> ()) {
//This resource is the same name as your xcdatamodeld contained in your project
guard let modelURL = Bundle.main.url(forResource: "MySampleListView", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: (modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = psc
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
queue.async {
guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
fatalError("Unable to resolve document directory")
}
let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
//The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
DispatchQueue.main.sync(execute: completionClosure)
} catch {
fatalError("Error migrating store: (error)")
}
}
}
}
I am trying to access that object from Appdelegate class :-
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
managedOBJ = Cmodel(completionClosure: {
DispatchQueue.main.async {
self.context = self.managedOBJ?.managedObjectContext
}
})
saveValues()
// Override point for customization after application launch.
return true
}.
This is how I use it.
//Save Local DB
extension AppDelegate {
func saveValues() {
let testQuestionModel : Kishor = NSEntityDescription.insertNewObject(forEntityName: "Kishor", into: AppDelegate.getContext()) as! Kishor
testQuestionModel.name = "Kishor Da Pahalwani"
self.saveContext()
}
}
I am getting fatal error.
I don't know the reason but maybe saveValues() getting called before Core Data managed context object initialization? Or maybe I am initialising in wrong way?
saveValues()
I am trying to follow Apple Documentation but I don't know what I am missing.
1 Answer
1
saveValues is called outside the completionClosure. This is way you receive a fatal error. The Core Data stack is not ready.
saveValues
completionClosure
Can you explain what do you want to achieve?
Yeah Actually I want to initialise Core Data and I want to save and update and delete it from my model class. Thanks
– kishor0011
Aug 28 '17 at 12:50
@kishor0011 populate or initialize?
– Lorenzo B
Aug 28 '17 at 12:51
Initialize in my model class.
– kishor0011
Aug 28 '17 at 12:52
Not clear what you are asking @kishor0011
– Lorenzo B
Aug 28 '17 at 12:53
I want to initialize
– kishor0011
Aug 28 '17 at 12:54
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
simple demo for core data Add update delete have a look github.com/SanjeetVerma/…
– Bhupat Bheda
Aug 28 '17 at 12:55