I had the same issue with Unit-Tests and Core Data:
At first I came across "I can not find a model for the store." I fixed this with this thread: Cedar unit test execution error from command line
Secondly, I got the same error: "Could not create file, code = 2"
Then I looked at the urls and saw that:
The URLs for NSPersistentStoreCoordinator and NSManagedObjectModel are pretty different. But only when I perform Unit-Testing and only after fixing the first error.
Typically, the model is located in "/ some / path / <DataModelFile> .app / <DataModel> .momd /
Sqlite is located in "some / path / Documents / <SQLiteFile> .sqlite
Thus, I use the following code to get the correct URLs when testing and running:
NSBundle *bundle = [NSBundle bundleForClass:[self class]]; NSURL *modelURL = [bundle URLForResource:@"WinNav" withExtension:@"momd"]; basePath = @""; NSArray *arr = [modelURL pathComponents]; for (int i=0; i<[arr count]-2; i++) { basePath = [basePath stringByAppendingString:[arr objectAtIndex:i]]; if (i > 0) basePath = [basePath stringByAppendingString:@"/"]; } NSLog(@"modelURL: %@", modelURL); NSURL *storeUrl = [NSURL fileURLWithPath:[basePath stringByAppendingString:@"/Documents/Locations.sqlite"]];
If I remember correctly, I had to create a "Documents" folder in which the sqlite file is stored.
Any comments / suggestions if this works for you or how to do it better are appreciated.
source share