Reputation: 5061
I have a framework project and getting that strange error when I try to unit test my classes.
here is code suggested by Andrew Bancroft to get in memoryNSManagedObjectContext
func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("Adding in-memory persistent store failed")
}
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
But whenever I try to insert an object (or any other db operation) by this code
let newLocationMO = NSEntityDescription.insertNewObject(forEntityName: table, into: context) as! LocationMO
It crashes with error mentioned in title.
I also tried to test with real context, so I import my framework to a temporary project and get context from AppDelegate auto-generated code but it crashes with same error as if it doesn't see my .xcdatamodeld
definition.
Note: I checked all typos and that no file is missing.
Maybe it is not allowed to have Core Data in framework project ? Any links or example of core data usage in framework project is highly appreciated.
Upvotes: 0
Views: 325
Reputation: 70936
You can use Core Data in a framework but you need to make sure that your code knows that it's in a framework. The most likely source of trouble is this line:
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
If you're in a framework, your model is not in the main bundle. You're telling it to look in the wrong place, so it's not finding the model file.
You probably want to change that to Bundle(for: type(of:self))
so that you'll be looking in the same bundle that contains the framework classes.
Upvotes: 1