I have a pre-existing project to which I've added Core Data models. I added the Core Data framework, added a data model with entities, and included it in my app's target, along with some generated NSManagedObject
classes. It compiles nicely, and now I'd like to add some tests for the entities I've created. Following these instructions, I've set up a logic test base class with a setUp
method like so:
- (void)setUp {
model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSLog(@"model: %@", model);
coord = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
store = [coord addPersistentStoreWithType:NSInMemoryStoreType
configuration:nil
URL:nil
options:nil
error:NULL];
ctx = [[NSManagedObjectContext alloc] init];
[ctx setPersistentStoreCoordinator:coord];
}
This compiles and all the objects are created. However, the model has no entities! The NSLog()
output looks like so:
2011-10-29 23:56:58.941 otest[42682:3b03] model: (<NSManagedObjectModel: 0x19c6780>) isEditable 1, entities {
}, fetch request templates {
}
So where are my entities? I've poked around the bundle, and there are no .momd
files, either. Have I missed some crucial step to get my models to build?
I did some additional Duck Duck Going and managed to find the information I needed in the this answer. The upshot is that, because a test target doesn't use a "main" bundle, I have to instantiate the test bundle. So instead of this line:
model = [NSManagedObjectModel mergedModelFromBundles:nil];
I now have these three lines:
NSBundle *bundle = [NSBundle bundleWithIdentifier:@"com.example.LogicTests"];
NSURL *url = [bundle URLForResource:@"MyModels" withExtension:@"momd"];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:url];
The bundle identifier comes directly from my target build info, while "MyModels" comes from my data model file, which is named "MyModels.xcdatamodeld" and included in the app bundle as "MyModels.momd". And that, of course, contains my models.