I'm developing a library for iOS using Swift 5, and I want this library to use CoreData independent of the application which consumes that library and this is what I've done so far:
- Created the entities with their respective data types
- Created the
.xcdatamodeldfile, which contains the entities - Created a
CoreDataManagerwhich looks like this:
// MARK: - CoreDataManager
final class CoreDataManager {
static let shared = CoreDataManager()
private static let defaultObject = NSManagedObject.init()
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Audit")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
}
And the trouble is I'm trying to get the context by:
let coreDataManager = CoreDataManager.shared
let context = coreDataManager.persistentContainer.viewContext
and context is returning nil
please help
I solved it, and apparently the trouble was that the ios application where I wanted to use my library wasn't finding the
.xcdatamodeldfile which resulted in a uselessNSPersistentContainerobject, which also meant thatlet context = persistentContainer.viewContextwasnil.In order to avoid this kind of troubles in the future, I'll left a list of important considerations when working with CoreData and swift libraries.
Key things to consider
s.resources = "path/to/model.xcdatamodeld"This will produce a folder named "Resources" in your Pods target:NSPersistentContainername.to
And even when I'm not sure if that makes sense, It could work for you.
Finally I'll leave the code that worked for me
And to get the context outside
Hope you guys find it helpful!!